题解 | #高精度整数加法#
高精度整数加法
https://www.nowcoder.com/practice/49e772ab08994a96980f9618892e55b6
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main(String[] args) { BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); String a, b, and2 = ""; try { a = r.readLine(); b = r.readLine(); } catch (IOException e) { throw new RuntimeException(e); } char[] chs1 = a.toCharArray(); char[] chs2 = b.toCharArray(); int[] arr1 = new int[10001]; int[] arr2 = new int[10001]; int[] arr3 = new int[10001]; int i, j = 0, k = 0, l = chs1.length, t; boolean lift = false; for (i = l - 1; i > -1; i--) {//字符串反向,便于计算 arr1[j++] = chs1[i] - '0'; } l = chs2.length; for (i = l - 1; i > -1; i--) {//字符串反向,便于计算 arr2[k++] = chs2[i] - '0'; } i = 0; while (i < 10001) { t = arr1[i] + arr2[i];//计算该位之和 if (lift) t++;//如果前一位有进1,则t自加 if (t > 9) {//如果进1 lift = true; t -= 10; } else lift = false; arr3[i] = t; i++; } i = Math.max(j, k); if (arr3[i] == 0) i--; while (i > -1) { and2 = and2 + arr3[i]; i--; } System.out.print(and2); } }