Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 8 of 8

Thread: Counting Addition "Carries"

  1. #1
    Member Staticity's Avatar
    Join Date
    Jul 2011
    Location
    Texas
    Posts
    105
    My Mood
    Inspired
    Thanks
    3
    Thanked 5 Times in 5 Posts

    Default Counting Addition "Carries"

    So, I just came back from a CS Competition, and there was this one question that asked this:
    "You will be given a .in file that will contain a number "n" which is the number of times to loop the program. The next lines will consist of two integers each that you will need to add. Develop a program to determine the number of arithmetic carries during this process"

    For example: 9 + 1 = 10 ... You carried once

    Data Input:
    3
    123 456
    555 555
    469 101

    Output:
    0
    3
    1

    So here's my code that gave me the correct answers for the provided input:

    import java.util.*;
     
    public class friday {
    	public static void main(String args[]){
    		Scanner scan = new Scanner(System.in);
    		System.out.println("Enter number of times to run");
    		int count = scan.nextInt();
    		while(count > 0){
    			System.out.println("Enter A:");
    			int a = scan.nextInt();
    			System.out.println("Enter B:");
    			int b = scan.nextInt();
    			String aword = a+"";
    			String bword = b+"";
    			char array1[] = aword.toCharArray();
    			char array2[] = bword.toCharArray();
    			int carries = 0;
     
    			for(int i = array2.length; i > 0; i--){
    				if((array1[i-1] + array2[i-1]) > 9+48+48){
    					carries++;
    				}
    			}
     
    			System.out.println(carries);
    			count--;
    		}
     
    	}
    }

    It doesn't work if the number's lengths are variable.. like A has a length of 2, and B has a length of 3.. It won't work that way, or if you have 999 + 1, the logic behind it wouldn't work either... Can someone point me in the correct direction? My friend who was in the advanced division told me he would use recursion.. But his logic was kind of skewed when he gave me an answer.. Any help would be Greatly Appreciated.
    Simplicity calls for Complexity. Think about it.


  2. #2
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Counting Addition "Carries"

    The simplest way is to take your code and force the two arrays to be the same length (whichever is longer). You can do this by adding zeros to the left ("011" = "11" numerically, should work with your code).

  3. #3
    Member Staticity's Avatar
    Join Date
    Jul 2011
    Location
    Texas
    Posts
    105
    My Mood
    Inspired
    Thanks
    3
    Thanked 5 Times in 5 Posts

    Default Re: Counting Addition "Carries"

    I don't believe it would work with 49 + 51..
    .. Because 9 + 1 is greater than 9 and carries a 1..
    However, the 1 doesn't carry over to 5 + 4.. so 5+4 = 9 and won't add a carry..

    To do the carrying properly, could I have a separate integer that is set to 0 or 1 depending on the if statement? And it resets back to 0 or 1 after the if statement has been executed? Also, how would I add zeros to the left? I'm not entirely sure on how to do this.
    Simplicity calls for Complexity. Think about it.

  4. #4
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Counting Addition "Carries"

    Just add an extra zero. Adding two numbers can never go more than 1 digit over the longer of the two numbers. You will need a separate carry variable.

    049 + 051 = 100

    You'd count 2 carries.

    adding zeros to the left:

    if(aword.length() > bword.length())
    {
        // normalize to aword.length() + 1
        aword = "0" + aword;
        int zeros_to_add = aword.length() - bword.length()+1;
        for(int i = 0; i < zeros_to_add; ++i)
        {
            bword = "0" + bword;
        }
    }
    else
    {
        // ... basically the same code, except bword is the longer one now. You get handling of equal length numbers here, too
    }
    Last edited by helloworld922; October 8th, 2011 at 09:46 PM.

  5. The Following User Says Thank You to helloworld922 For This Useful Post:

    Sheldon.Cooper (February 9th, 2013)

  6. #5
    Member Staticity's Avatar
    Join Date
    Jul 2011
    Location
    Texas
    Posts
    105
    My Mood
    Inspired
    Thanks
    3
    Thanked 5 Times in 5 Posts

    Default Re: Counting Addition "Carries"

    Say I wanted to add 199991 and 9... The leading 0 wouldn't really work. Is there a better resolution? I know I could use a For loop to add 0 to the beginning until the lengths are the same, but that doesn't seem to clean.
    Simplicity calls for Complexity. Think about it.

  7. #6
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Counting Addition "Carries"

    I don't see why it wouldn't work (at least in theory, there may be some bugs in the implementation):

    0199991
    0000009
    _______
    0200000

    It should count 5 carries.

    To be honest the for-loops isn't a very clean way to do it. There is another way to do it by creating arrays after you've converted the strings to char arrays and copying the data over and filling the rest with '0', but either way it's going to look messy because you're trying to discretize a very simple operation and quantify something rather "odd". And this isn't the only method available, it's just the one I chose because I assumed your original code worked already with equal-length strings.

  8. #7
    Member Staticity's Avatar
    Join Date
    Jul 2011
    Location
    Texas
    Posts
    105
    My Mood
    Inspired
    Thanks
    3
    Thanked 5 Times in 5 Posts

    Default Re: Counting Addition "Carries"

    import java.util.*;
     
    public class friday {
    	public static void main(String args[]){
    		Scanner scan = new Scanner(System.in);
    		System.out.println("Enter number of times to run");
    		int count = scan.nextInt();
    		while(count > 0){
    			System.out.println("Enter A:");
    			int a = scan.nextInt();
    			System.out.println("Enter B:");
    			int b = scan.nextInt();
    			String aword = a+"";
    			String bword = b+"";
    			int carries = 0;
    			int carry = 0;
     
    			if(aword.length() < bword.length())
    				for(int c = aword.length(); c < bword.length(); c++)
    					aword = "0" + aword;
    			if(bword.length() < aword.length())
    				for(int d = bword.length(); d < aword.length(); d++)
    					bword = "0" + bword;
     
    				System.out.println(aword);
    				System.out.println(bword);
    				char array1[] = aword.toCharArray();
    				char array2[] = bword.toCharArray();
     
    			for(int i = array2.length; i > 0; i--){
    				if((array1[i-1] + array2[i-1]) + carry> 9+48+48){
    					carry = 1;
    					carries++;
    				}
    				else
    					carry = 0;
    			}
     
    			System.out.println(carries);
    			count--;
    		}
     
    	}
    }

    This works just fine.. However, I'm sure this can be done recursively... I'll attempt to figure it out. Thanks for your advice!
    Simplicity calls for Complexity. Think about it.

  9. The Following User Says Thank You to Staticity For This Useful Post:

    Sheldon.Cooper (February 9th, 2013)

  10. #8
    Junior Member
    Join Date
    Feb 2013
    Posts
    1
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Counting Addition "Carries"

    Thank You Very Much for the code, I've been looking for this code almost a week now.

Similar Threads

  1. Replies: 7
    Last Post: August 13th, 2011, 01:22 AM
  2. Replies: 6
    Last Post: November 12th, 2010, 04:40 AM
  3. Java says:"Hello World". I say:"It works!"
    By Davidovic in forum Member Introductions
    Replies: 4
    Last Post: June 29th, 2010, 07:13 AM
  4. "java.lang.NoSuchMethodError: main" and "fatal exception occured."
    By joachim89 in forum What's Wrong With My Code?
    Replies: 2
    Last Post: January 10th, 2010, 08:35 AM
  5. Replies: 4
    Last Post: August 13th, 2009, 05:54 AM