思路:
1.将两个大整数看成是两个字符串
2.将两个字符串存入到数组中,按照高位在后,低位在前的方式存储
3.使用遍历的方法,将两个数组按位相加并且进位,存放在数组C中
4.最后将数组C按照倒序输出得到最终结果
代码如下:
package cn.liyi.day04;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Demo791 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a = sc.next();
String b = sc.next();
List<Integer> A = new ArrayList<>();
List<Integer> B = new ArrayList<>();
for (int i = a.length() - 1; i >= 0; i--) {
A.add(a.charAt(i) - '0');
}
for (int i = b.length() - 1; i >= 0; i--) {
B.add(b.charAt(i) - '0');
}
List<Integer> C = add(A, B);
for (int i = C.size() - 1; i >= 0; i--) {
System.out.print(C.get(i));
}
}
public static List<Integer> add(List<Integer> A, List<Integer> B) {
List<Integer> C = new ArrayList<>();
int t = 0;
for (int i = 0; i < A.size() || i < B.size(); i++) {
if (i < A.size())
t += A.get(i);
if (i < B.size())
t += B.get(i);
C.add(t % 10);
t /= 10;
}
if(t != 0)
C.add(t);
return C;
}
}