题解 | #高精度整数加法#
高精度整数加法
https://www.nowcoder.com/practice/49e772ab08994a96980f9618892e55b6
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNext()) { // 注意 while 处理多个 case String as = in.nextLine(); String bs = in.nextLine(); StringBuilder out = new StringBuilder();//用于存放相加后的结果 int l = Math.max(as.length(), bs.length()); int subl = Math.abs(as.length() - bs.length()); //as 和 bs 长度不等时,短的那个前面补0 if (subl != 0) { String sub0 = ""; for (int j = 0; j < subl; j++) { sub0 = sub0.concat("0"); } if (as.length() > bs.length()) { bs = sub0.concat(bs); } else if (bs.length() > as.length()) { as = sub0.concat(as); } } int pre = 0; //存放单数字相加结果的十位数,为0或1; for (int i = l - 1; i >= 0; i--) { char ai = as.charAt(i); char bi = bs.charAt(i); int num = ai - '0' + bi - '0' + pre; pre = 0; int num0 = num % 10; if (i == 0) { out.insert(0, Integer.toString(num)); break; } if (num >= 10) { out.insert(0, Integer.toString(num0)); pre += 1; } else if (num < 10) { out.insert(0, Integer.toString(num0)); } } System.out.println(out.toString()); } } }