题解 | #高精度整数加法#
高精度整数加法
https://www.nowcoder.com/practice/49e772ab08994a96980f9618892e55b6
题解:使用字符串模拟加法运算,从尾到头进行运算,并将结果保存在StringBuilder中,运算完之后需要反转。难点在于对进位的处理。
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); Scanner scanner = new Scanner(br); String str1 = scanner.nextLine(); String str2 = scanner.nextLine(); String result = getHighPrecisionIntAddition(str1,str2); System.out.println(result); } private static String getHighPrecisionIntAddition(String str1, String str2) { if (str1 == null || str1.length() == 0) return str2; if (str2 == null || str2.length() == 0) return str1; // 从尾到头计算低位的和 int i = str1.length()-1,j = str2.length()-1; int carry = 0,sum; StringBuilder builder = new StringBuilder(); while (i >= 0 || j >= 0){ if (i >= 0 && j >= 0){ sum = Integer.valueOf(str1.substring(i, i + 1)) + Integer.valueOf(str2.substring(j, j + 1)); i--; j--; }else if (i >= 0 && j < 0){ sum = Integer.valueOf(str1.substring(i, i + 1)); i--; }else{ sum = Integer.valueOf(str2.substring(j, j + 1)); j--; } // 保存计算结果 builder.append((sum + carry) % 10); // 处理进位 if ((sum + carry) >= 10){ carry = 1; }else carry = 0; } // 最终进位 if (carry == 1) builder.append(carry); // 结果需要反转 return builder.reverse().toString(); } }