43. Multiply Strings

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class Solution {
public String multiply(String num1, String num2) {
if (num1.equals("0") || num2.equals("0")) {
// 0 与任何数字相乘等于 0, 此处特判是便于后续数字数组转换字符串前导 0 的简单处理
// 如:0 * 9133 = 0, 如不在此处进行特判,则数字数组为 00000, 去掉首个前导 0 后依然为 0000 而不是 0, 导致不能 AC
return "0";
}

// index: 0 1 2
// num1: 1 2 3
// num2: 4 5 6
// ------------------
// 1 8
// 1 2
// 6
// 1 5
// 1 0
// 5
// 1 2
// 8
// 4
// ------------------
// 5 6 0 8 8
// index: 0 1 2 3 4 5

int[] nums = new int[num1.length() + num2.length()];
for (int i = num2.length() - 1; i >= 0; i--) {
for (int j = num1.length() - 1; j >= 0; j--) {
int x = num2.charAt(i) - '0';
int y = num1.charAt(j) - '0';
int product = nums[i + j + 1] + x * y;
int carry = product / 10;
int num = product % 10;

nums[i + j + 1] = num;
nums[i + j] += carry;
}
}

StringBuilder sb = new StringBuilder();
for (int i = 0; i < nums.length; i++) {
// 只有索引为 0 的数字可能为 0, 如 100 * 100 = 010000
if (i == 0 && nums[0] == 0) {
continue;
}
sb.append(nums[i]);
}
return sb.toString();
}
}

References

43. Multiply Strings