43-字符串相乘

43-字符串相乘

力扣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;
}
//转换成字符串,注意开头为0和全0情况
StringBuilder sb = new StringBuilder();
boolean flag = false; //遇到开头不为0时才能插入
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();
}

其他字符串类型的题目点这里

#
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×