close

題目概要:

計算共進位幾次。

解題方向:

使用StringBuilder建立String,主要是因為StringBuilder提供字串反轉的功能,把字串反轉後計算進位幾次會比較方便。開始計算是否進位,並印出結果。

程式碼:

//Java
import java.util.Scanner;
class uva10035{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
while(true){
//讀入2組數字,並變成字串形式。
StringBuilder st1=new StringBuilder(sc.next());
StringBuilder st2=new StringBuilder(sc.next());
//當輸入為0 0終止程式。
if(st1.charAt(0)=='0' && st2.charAt(0)=='0') break;
//字串反轉。方便加法。
st1.reverse();
st2.reverse();
//找出字串最大值、最小值。
int maxSize=Math.max(st1.length(),st2.length());
int minSize=Math.min(st1.length(),st2.length());
int c=0; //進位數字。
int count=0; //計算進位幾次。
//add
for(int i=0;i<maxSize;i++){
if(i<minSize){
int temp=st1.charAt(i)-48+st2.charAt(i)-48+c;
c=temp/10;
}else{
if(st1.length()==maxSize){
int temp=st1.charAt(i)-48+c;
c=temp/10;
}else{
int temp=st2.charAt(i)-48+c;
c=temp/10;
}
}
if(c!=0) count++;
}
//Output
if(count==0){
System.out.println("No carry operation.");
}else if(count==1){
System.out.println(count+" carry operation.");
}else{
System.out.println(count+" carry operations.");
}
}
}
}
view raw uva10035.java hosted with ❤ by GitHub

arrow
arrow
    文章標籤
    Java
    全站熱搜
    創作者介紹
    創作者 a7069810 的頭像
    a7069810

    紀錄自己的程式人生

    a7069810 發表在 痞客邦 留言(0) 人氣()