这题如果如果开挂的话, 可以直接用BigInteger类。
思路
用了三个辅助方法:
1. 大数相加。(顺带实现的,毕竟乘法的过程中需要用到加法)
2. 大数 * 一位数字 (很基础的步骤,列竖式的时候用到)
3. 去除结果的前导0。(很容易忽略,如0 * 123 结果会是 000,正确的结果应该是0)
然后就是利用这三个辅助方法得到最终结果。写法虽然直接但是有点繁琐,后续会考虑优化一下。
1 class Solution { 2 public String multiply(String num1, String num2) { 3 String ans = "0"; 4 String carry = ""; 5 for (int i = num2.length() - 1; i >= 0; i--) { 6 String tmp = singleMultiply(num1, num2.charAt(i)); 7 tmp = tmp + carry; 8 ans = add(tmp, ans); 9 carry = carry + "0"; 10 } 11 12 //记得要去除leading zeros 13 return trimZeros(ans); 14 } 15 16 public String add(String num1, String num2) { 17 StringBuilder sb = new StringBuilder(); 18 int n1 = num1.length(); 19 int n2 = num2.length(); 20 int i = n1 - 1, j = n2 - 1; 21 int carry = 0; 22 while (i >= 0 && j >= 0) { 23 int a = num1.charAt(i) - ‘0‘; 24 int b = num2.charAt(j) - ‘0‘; 25 int tmp = (a + b + carry) % 10; 26 carry = (a + b + carry) / 10; 27 sb.insert(0, tmp); 28 i--; j--; 29 } 30 while (i >= 0) { 31 int a = num1.charAt(i) - ‘0‘; 32 int tmp = (a + carry) % 10; 33 carry = (a + carry) / 10; 34 sb.insert(0, tmp); 35 i--; 36 } 37 while (j >= 0) { 38 int b = num2.charAt(j) - ‘0‘; 39 int tmp = (b + carry) % 10; 40 carry = (b + carry) / 10; 41 sb.insert(0, tmp); 42 j--; 43 } 44 if (carry > 0) { 45 sb.insert(0, carry); 46 } 47 return sb.toString(); 48 } 49 50 public String singleMultiply(String num, char c) { 51 int d = c - ‘0‘; 52 int carry = 0; 53 StringBuilder sb = new StringBuilder(); 54 for (int i = num.length() - 1; i >= 0; i--) { 55 int tmp = ((num.charAt(i) - ‘0‘) * d + carry) % 10; 56 carry = ((num.charAt(i) - ‘0‘) * d + carry) / 10; 57 sb.insert(0, tmp); 58 } 59 if (carry > 0) { 60 sb.insert(0, carry); 61 } 62 return sb.toString(); 63 } 64 65 public String trimZeros(String s) { 66 StringBuilder sb = new StringBuilder(s); 67 while (sb.length() > 1 && sb.charAt(0) == ‘0‘) { 68 sb.deleteCharAt(0); 69 } 70 return sb.toString(); 71 } 72 }
原文地址:https://www.cnblogs.com/hiyashinsu/p/10727359.html
时间: 2024-10-07 23:58:33