题解 | #高精度整数加法#
高精度整数加法
https://www.nowcoder.com/practice/49e772ab08994a96980f9618892e55b6
直接调库
面试官:你觉得自己很幽默?
import java.math.BigInteger;
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNext()) { // 注意 while 处理多个 case
BigInteger num1 = new BigInteger(in.next());
BigInteger num2 = new BigInteger(in.next());
System.out.println(num1.add(num2));
}
}
}
自行模拟
注意最后一位的进位,以及 StringBuilder 的 append 函数是接受直接输入 int 型参数的,它会直接输出字符串形式的数字,类似于 num+"",而不是输出其 ASCII 码对应的字符。
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNext()) { // 注意 while 处理多个 case
String num1 = in.next();
String num2 = in.next();
StringBuilder sb = new StringBuilder();
int cin = 0;
int res = 0;
for (int i = 0; i < num1.length() || i < num2.length(); i++) {
int n1 = i < num1.length() ? num1.charAt(num1.length() - 1 - i) - '0' : 0;
int n2 = i < num2.length() ? num2.charAt(num2.length() - 1 - i) - '0' : 0;
res = n1 + n2 + cin;
sb.append(res % 10);
cin = res / 10;
}
if (res >= 10) sb.append('1');
System.out.println(sb.reverse());
}
}
}
