题解 | #高精度整数加法#
高精度整数加法
http://www.nowcoder.com/practice/49e772ab08994a96980f9618892e55b6
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
String s1 = in.nextLine();
String s2 = in.nextLine();
char[] c1 = s1.toCharArray();
char[] c2 = s2.toCharArray();
char[] res = new char[Math.max(c1.length, c2.length)+1];
int l1 = c1.length-1;
int l2 = c2.length-1;
int count = Math.max(c1.length, c2.length);
while(l1 >= 0 && l2 >= 0){
int sum = res[count] + c1[l1] + c2[l2] - (2*'0');
if(sum >= 10){
sum = sum - 10;
res[count-1] = 1;
}
res[count] = (char)(sum + '0');
l1--;
l2--;
count--;
}
if(res[count] == 1){
res[count] = '1';
}
if(l2 >= 0){
for(int i = l2; i>=0; i--){
if(res[count] == '1'){
if(res[count] + c2[i] - 2*'0' >= 10){
res[count] = '0';
res[count-1] = '1';
}else{
res[count] = (char)(c2[i]+1);
}
}else{
res[count] = (char)c2[i];
}
count--;
}
}else if(l1 >= 0){
for(int i = l1; i>=0; i--){
if(res[count] == '1'){
if(res[count] + c1[i] - 2*'0' >= 10){
res[count] = '0';
res[count-1] = '1';
}else{
res[count] = (char)(c1[i]+1);
}
}else{
res[count] = (char)c1[i];
}
count--;
}
}
String ans = String.valueOf(res);
if(ans.charAt(0) < '0' || ans.charAt(0) > '9'){
ans = ans.substring(1);
}
System.out.println(ans);
}
}
查看16道真题和解析