题解 | #高精度整数加法#
考虑两个数字不同长度的情况。
import java.io.*;
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String str = "";
while (( str = reader.readLine() ) != null) {
String str2 = reader.readLine();
if (str.length() > str2.length()) {
add(str, str2);
} else {
add(str2, str);
}
}
}
public static void add(String str1, String str2) {
int n1 = str1.length();
int n2 = str2.length();
List<Integer> list = new ArrayList<>();
// 向上一位进的数
int sign = 0;
for (int i = 0; i < n1; i++) {
if (n2-i-1 >= 0) {
int tmp = Integer.parseInt(str1.substring(n1-i-1, n1-i)) +
Integer.parseInt(str2.substring(n2-i-1, n2-i));
if (tmp > 9) {
if (i == n1-1) {
list.add(tmp + sign);
} else {
list.add(tmp % 10 + sign);
//向上进一
sign = 1;
}
} else {
if (tmp + sign > 9) {
// 每种情况都要考虑越界问题
if (i == n1-1) {
list.add(10);
} else {
list.add(0);
sign = 1;
}
} else {
list.add(tmp + sign);
sign = 0;
}
}
}else {
int tmp = Integer.parseInt(str1.substring(n1-i-1, n1-i)) + sign;
if (tmp > 9) {
if (i == n1-1) {
// 最后一位了直接加10
list.add(10);
} else {
list.add(0);
sign = 1;
}
} else {
list.add(tmp);
sign = 0;
}
}
}
for (int i = list.size() - 1; i >= 0; i--) {
System.out.print(list.get(i));
}
}
}
查看10道真题和解析