题解 | #高精度整数加法#
高精度整数加法
http://www.nowcoder.com/practice/49e772ab08994a96980f9618892e55b6
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
String a = in.next();
String b = in.next();
boolean f = a.length()>=b.length();
boolean flag = false;
char[] cBig = f?a.toCharArray():b.toCharArray();
char[] cSmall = f?b.toCharArray():a.toCharArray();
//相加后的字符数组
char[] newC = new char[cBig.length+1];
Arrays.fill(newC,'0');
int t = 0;
//以短字符串为基准,分别将两字符串从后面的每一个字符相加
for(int i = cSmall.length-1; i>=0; i--){
if(flag){
t = cBig[i+cBig.length-cSmall.length] + cSmall[i] + 1 - 48 - 48;
}else{
t = cBig[i+cBig.length-cSmall.length] + cSmall[i] - 48 - 48;
}
flag = false;
//相加大于10,进位
if(t>=10){
flag = true;
t -= 10;
}
newC[i+cBig.length-cSmall.length+1] = (char)(t + 48);
}
//短字符串相加完成后,将长字符串剩余字符给newC
int j = newC.length-cSmall.length-1;
for(; j>=newC.length-cBig.length; j--){
if(flag){
t = (char)(cBig[j-1] + 1 - 48);
flag = false;
if(t>=10){
flag = true;
t -= 10;
}
newC[j] = (char)(t + 48);
}else{
newC[j] = cBig[j-1];
}
}
if(flag){
newC[0] = (char)1+48;
System.out.print(String.copyValueOf(newC));
}else{
System.out.print(String.copyValueOf(newC).substring(1,newC.length));
}
}
}
}