自己写的。大数加法。字符串转int数组。
高精度整数加法
https://www.nowcoder.com/practice/49e772ab08994a96980f9618892e55b6
import java.util.*; import java.lang.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNextLine()) { String str1 = in.nextLine(); String str2 = in.nextLine(); StringBuffer sb = new StringBuffer(str1); str1 = sb.reverse().toString(); //反转加数a sb = new StringBuffer(str2); str2 = sb.reverse().toString(); //反转加数b int n = Math.max(str1.length(), str2.length()) + 1; //长度+1,为最高位有进位做准备 int[] a = new int[n]; int[] b = new int[n]; int i = 0; for (char ch : str1.toCharArray()) { a[i++] = ch - '0'; //string转int } for (i = str1.length(); i < n; i++) { a[i] = 0; //最高位前面补零 } i = 0; for (char ch : str2.toCharArray()) { b[i++] = ch - '0'; } for (i = str2.length(); i < n; i++) { b[i] = 0; } int add = 0; //进位 for (i = 0; i < n; i++) { int sum = a[i] + b[i] + add; add = sum / 10; a[i] = sum % 10; //将结果保存在a中 } String res = ""; for (i = 0; i < n; i++) { if (i == n - 1 && a[i] == 0) { //如果最高位没有进位,则之前补的0要舍弃。 break; } res += String.valueOf(a[i]); //将答案依次附加到结果字符串中 } sb = new StringBuffer(res); //反转得到正确的结果 System.out.println(sb.reverse().toString()); } } }