题解 | #高精度整数加法#
高精度整数加法
https://www.nowcoder.com/practice/49e772ab08994a96980f9618892e55b6
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextLine()) { // 注意 while 处理多个 case
char[] s1 = in.nextLine().toCharArray();
char[] s2 = in.nextLine().toCharArray();
Stack<Integer> stack = new Stack<>();
int carryBit = 0;
int i = s1.length - 1, j = s2.length - 1;
while (i >= 0 && j >= 0) {
int d1 = s1[i] - '0';
int d2 = s2[j] - '0';
int sum = d1 + d2 + carryBit;
stack.push((sum % 10));
carryBit = sum / 10;
i--;
j--;
}
if ( i > j) {
while (i >= 0) {
int sum = s1[i] - '0' + carryBit;
stack.push((sum % 10));
carryBit = sum / 10;
i--;
}
} else if (i < j) {
while (j >= 0) {
int sum = s2[j] - '0' + carryBit;
stack.push((sum % 10));
carryBit = sum / 10;
j--;
}
}
if(carryBit > 0){
stack.push(carryBit);
}
while(!stack.isEmpty()){
System.out.print(stack.pop());
}
}
}
}