大數(shù)求和
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str;
while ( (str= br.readLine())!=null){
// 先字符串反轉(zhuǎn)
StringBuilder str1 = new StringBuilder(str).reverse();
StringBuilder str2 = new StringBuilder(br.readLine()).reverse();
int length1 = str1.length();
int length2 = str2.length();
int max = length1>length2 ? length1:length2;
// 字符串補齊
if(length1>length2){
for(int i=0; i<length1-length2; i++){
str2.append("0");
}
}else if(length1<length2){
for(int i=0; i<length2-length1; i++){
str1.append("0");
}
}
int[] arr = new int[max+1];
for (int i=0;i<max;i++){
int n1 = Integer.valueOf(str1.charAt(i)-'0');
int n2 = Integer.valueOf(str2.charAt(i)-'0');
if (arr[i] + n1 + n2 >=10){
arr[i] = arr[i] + n1 + n2 -10;
arr[i + 1] = 1;
}else {
arr[i] = arr[i] + n1 + n2;
}
}
StringBuilder sb = new StringBuilder();
if (arr[max]!=0){
sb.append(arr[max]);
}
for (int i=max-1;i>=0;i--){
sb.append(arr[i]);
}
System.out.println(sb.toString());
}
}
}
大數(shù)乘法
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者