【JAVA】UVA 10035 - Primary Arithmetic

題目原文:https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=12&page=show_problem&problem=976

Sample Input
123 456
555 555
123 594
0 0
Sample Output
No carry operation.
3 carry operations.
1 carry operation.

題目大意:判斷兩整數相加後產生多少個進位,當兩數皆為0則停止程式。
特別要注意的是,本題所有變數都為int,因此不會有小數的出現。

123+456作為範例,首先第一輪sum=123%10+456%10+carry = 3+6+0 = 9 , sum沒有大於10所以carries保持為0,carry=sum/10所以也是0 , 接著a = a/10 => 123/10 = 12, b = b/10 => 456/10 = 45;

第二輪sum = 12%10+45%10+carry = 2+5+0 = 7 , carry=0,carries=0 , a = 12/10 = 1 , b = 45/10 = 4;

第三輪sum = 1%10+4%10+carry = 1+4+0 = 5 ,carry=0,carries=0 , a = 1/10 = 0 , b = 4/10 = 0 , 是以a與b皆為0,程式結束。

而最終carries = 0 , 所以output為No carry operation.

import java.util.*;
public class main{
    public static void main(String[] args) {
            Scanner sc=new Scanner(System.in);
            
            while(true){
            int a=sc.nextInt(),b=sc.nextInt();
            if(a==0&&b==0){ //當兩數皆為0則停止程式
            	break;
            }
        	
        	int carry=0,carries=0;
        	
        	while(a!=0||b!=0){ //a或者b任意一個不為0則繼續判斷
        	
        	int sum = a%10+b%10+carry; //從個位數慢慢往前推,判斷有無進位
        	
        	if(sum>=10){
        		++carries;
        	}
        	
        	carry = sum/10;
        	a /= 10;  // a=a/10 每判斷完一個位數,就將它捨去
        	b /= 10;  // b=b/10 每判斷完一個位數,就將它捨去
        	
        	}
        	
        	if(carries==0){
        	System.out.println("No carry operation.");
        	}else if(carries==1){
        	System.out.println("1 carry operation.");
        	}else{
        	System.out.println(carries + " carry operations.");
        	}
            
            }
           
        }
    }