UVA – 10035 – Primary Arithmetic

  • ID : UVA – 10035 – Primary Arithmetic
  • Submissions :
    • Java – Accepted
  • Difficulty : Easy
  • Type : Simple Algebra
  • Time for Submission : 1 Hour
  • Solution Description :
    • Divide the two numbers constantly by 10 until one of them reaches 0 till then check weather the sum of the previous carry, and the numbers mod10 that represent the right most digit.
    • carry will equal the result divided by 10 as the sum will never exceed 19. (9 + 9 + 1carry)
  • Problems :
    • watch out the short-circuit at the while loop.

import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) throws IOException {
		Scanner in = new Scanner(System.in);
		int a = 0,b = 0;
		ArrayList<String> list = new ArrayList<String>();

		while( (a=in.nextInt())==-1 || (b=in.nextInt())==-1 || true){
			if(a==0 && b==0) break;

			int count = count(a,b);

			if(count==0)
				list.add("No carry operation.");
			else if(count==1)
				list.add("1 carry operation.");
			else
				list.add( count + " carry operations.");

		}

		for(String ans : list)
		System.out.println(ans);
	}

	private static int count(int a, int b) {

		int sum, carry = 0,count = 0;

		while ((a > 0) || (b > 0)) {
		    sum = carry + (a % 10) + (b % 10);

		    if (sum >= 10) count++;

		    carry = sum / 10;
		    a /= 10;
	        b /= 10;
		}
		return count;
	}
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: