close
題目概要:
計算共進位幾次。
解題方向:
使用StringBuilder建立String,主要是因為StringBuilder提供字串反轉的功能,把字串反轉後計算進位幾次會比較方便。開始計算是否進位,並印出結果。
程式碼:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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."); | |
} | |
} | |
} | |
} |
文章標籤
全站熱搜