类似于ACM1003,当两个数特别大的时候,比如数百位长,这个时间没法用int,long等基本数据类型来表示,
这个时候我们要把它转化为字符串相加,具体实现如下:
static void aplusb(StringBuilder s1, StringBuilder s2) {
int l1 = s1.length(), l2 = s2.length();
int sum, tmp = 0;
if (l1 > l2) {
for (int i = l1 - 1, j = l2 - 1; j >= 0; i--, j--) {
sum = s1.charAt(i) - 48 + s2.charAt(j) - 48 + tmp;
tmp = sum / 10;
sum = sum % 10;
s1.setCharAt(i, (char) (sum + 48));
//System.out.println(sum);
}
for (int i = l1 - l2 - 1; i >= 0; i--) {
sum = s1.charAt(i) + tmp - 48;
//System.out.println(sum);
tmp = sum / 10;
sum = sum % 10;
s1.setCharAt(i, (char) (sum + 48));
}
if(tmp > 0)
System.out.println(tmp + "" + s1);
else
System.out.println(s1);
} else {
for (int i = l2 - 1, j = l1 - 1; j >= 0; i--, j--) {
sum = s2.charAt(i) - 48 + s1.charAt(j) - 48 + tmp;
tmp = sum / 10;
sum = sum % 10;
s2.setCharAt(i, (char) (sum + 48));
//System.out.println(sum);
}
for (int i = l2 - l1 - 1; i >= 0; i--) {
sum = s2.charAt(i) + tmp - 48;
//System.out.println(sum);
tmp = sum / 10;
sum = sum % 10;
s2.setCharAt(i, (char) (sum + 48));
}
if(tmp > 0)
System.out.println(tmp + "" + s2);
else
System.out.println(s2);
}
}