题解 | 高精度整数加法
高精度整数加法
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 的区别 String a = in.nextLine(); String b = in.nextLine(); StringBuilder sb = new StringBuilder(); int max = Math.max(a.length(), b.length()); if(a.length() < b.length()) { int x = b.length() - a.length(); for(int i = 0; i < x; i++) { a = "0" + a; } } else { int x = a.length() - b.length(); for(int i = 0; i < x; i++) { b = "0" + b; } } // 是否进位 boolean flag = false; for(int i = max - 1; i >=0; i--) { int m = Integer.valueOf(String.valueOf(a.charAt(i))); int n = Integer.valueOf(String.valueOf(b.charAt(i))); int result = m + n + (flag?1:0); sb.append(result%10); flag = result / 10 > 0; } if(flag) { sb.append("1"); } sb.reverse(); System.out.println(sb.toString()); } }