力扣43 字符串相乘
https://leetcode-cn.com/problems/multiply-strings/
思路:此题和大数相加有些类似,这种通过字符串模拟手算加法乘法的,仍然采用这种从高位到低位,进位和基数分开的方式,更加简洁方便
过程如下
代码如下
要注意基数数组和进位数组的长度,如上图最左边的8,也就是有可能首位进位,因此长度是len(num1 + num2)而不是len(num1 + num2 - 1)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| public String multiply(String num1, String num2) { int[] jiShu = new int[num1.length() + num2.length()]; int[] jinWei = new int[num1.length() + num2.length()]; for (int i = 0; i < num1.length(); i++) { for (int j = 0; j < num2.length(); j++) { int bit1 = num1.charAt(i) - '0'; int bit2 = num2.charAt(j) - '0'; int add = bit1 * bit2 + jiShu[i + j + 1]; jiShu[i + j + 1] = add % 10; jinWei[i + j] = add / 10 + jinWei[i + j]; } } int[] res = new int[jinWei.length]; for (int i = jinWei.length - 1; i >= 0; i--) { int num = jiShu[i] + jinWei[i] + res[i]; res[i] = num % 10; if (i - 1 < 0) break; res[i - 1] += num / 10; } StringBuilder sb = new StringBuilder(); boolean flag = false; for (int i = 0; i < res.length; i++) { if (res[i] != 0) flag = true; if (flag) sb.append(res[i]); } return "".equals(sb.toString()) ? "0" : sb.toString(); }
|
其他字符串类型的题目点这里