ECNU 1001 Problem A+B (Big Integer)
链接
https://acm.ecnu.edu.cn/problem/1001
题目
单点时限: 2.0 sec
内存限制: 256 MB
Give two positive integer a and b, calucate a+b.
Notice that ab is no more than 500 digits.
输入格式
The test case contain several lines. Each line contains two positive integer and .
输出格式
For each input line, output a line contain .
样例
input
2 3
1231231231823192 123123123123123
1000000000000000 1
output
5
1354354354946315
1000000000000001
思路
英文题目,大数加法,不过只有加法吗。
上面说了不少于500位,那么传统方法就不行了,只有用字符串来进行计算,这里就写一下思路。
先给两个字符串,转置。之后找到较短的那个,后面补0到二者等长,这里新建一个数组,存放每一位的加法,大于9也照样存放进来(其实可以省去补0),之后对于每一位,如果大于9,就只取个位放在原处,前面补一位,这是模拟进位。最后把全部转为字符串。思路是相对通用的,要是专门为了这道题可以再优化不少。
代码
public static void fun() {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String s1 = sc.next();
String s2 = sc.next();
StringBuilder a = new StringBuilder(s1);
StringBuilder b = new StringBuilder(s2);
a.reverse();
b.reverse();
int m = a.length();
int n = b.length();
int max = Math.max(m, n);
if (m < n) {
for (int i = m; i < n; i++) {
a.append('0');
}
} else {
for (int i = n; i < m; i++) {
b.append('0');
}
}
int[] ans = new int[max + 1];
for (int i = 0; i < max; i++) {
ans[i] = (a.charAt(i) - '0') + (b.charAt(i) - '0');
}
for (int i = 0; i < max; i++) {
ans[i + 1] += ans[i] / 10;
ans[i] %= 10;
}
StringBuilder result = new StringBuilder();
for (int i = 0; i < max; i++) {
result.append(ans[i]);
}
if (ans[max] != 0) {
result.append(ans[max]);
}
System.out.println(result.reverse().toString());
}
}