方法一 拆分字符串相加
import java.util.Scanner;
import java.math.BigInteger;
import java.util.Stack;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
String Str1 = in.nextLine();
String Str2 = in.nextLine();
System.out.println(addNumber(Str1, Str2));
}
public static String addNumber(String str1, String str2) {
int str1Length = str1.length() - 1;
int str2Length = str2.length() - 1;
int carry = 0;
Stack<Integer> stack = new Stack<>();
while (str1Length >= 0 || str2Length >= 0 || carry == 1) {
int temp = 0;
if (str1Length >= 0 && str2Length >= 0) {
temp = carry + str1.charAt(str1Length) - '0' + str2.charAt(str2Length) - '0';
str1Length = str1Length - 1;
str2Length = str2Length - 1;
} else if (str1Length >= 0 && str2Length < 0) {
temp = carry + str1.charAt(str1Length) - '0';
str1Length = str1Length - 1;
} else if (str2Length >= 0 && str1Length < 0) {
temp = carry + str2.charAt(str2Length) - '0';
str2Length = str2Length - 1;
} else {
temp = carry;
}
carry = temp / 10;
stack.push(temp % 10);
}
StringBuffer sb = new StringBuffer();
while (!stack.isEmpty()) {
sb.append(stack.pop());
}
return sb.toString();
}
}
方法二 使用BigInteger类,相加
import java.util.Scanner;
import java.math.BigInteger;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
BigInteger a = in.nextBigInteger();
BigInteger b = in.nextBigInteger();
System.out.println(a.add(b));
}
}