字符串相乘
给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式。
注意:不能使用任何内置的 BigInteger 库或直接将输入转换为整数。
示例 1:
输入: num1 = "2", num2 = "3"
输出: "6"
1
2
2
/**
* @param {string} num1
* @param {string} num2
* @return {string}
*/
var multiply = function(num1, num2) {
if(num1 === "0" || num2 === "0") return "0"
let len1 = num1.length
let len2 = num2.length
let maxLen = 0
let arr = []
for(let i = len1 - 1; i >=0; i--) {
let curArr = new Array(len1 - i - 1).fill(0)
let intPart = 0
for(let j = len2 - 1; j >=0; j--) {
let curRes = num1[i] * num2[j]
if(j === 0 && curRes + intPart >= 10) {
curArr.unshift(Math.floor((curRes + intPart)/10),(curRes + intPart)%10)
intPart = 0
} else {
curArr.unshift((curRes + intPart)%10)
intPart = Math.floor((curRes + intPart)/10)
}
}
arr.push(curArr)
}
maxLen = arr[arr.length - 1].length
for(let m = 0; m < arr.length; m++) {
if(arr[m].length < maxLen) {
while(arr[m].length < maxLen) {
arr[m].unshift(0)
}
}
}
let res = []
let resIntPart = 0
for(let n = maxLen - 1; n >= 0; n--) {
let curRes = 0
for(let m = 0; m < arr.length; m++) {
curRes += arr[m][n]
}
if(n === 0 && curRes + resIntPart >= 10) {
res.unshift(Math.floor((curRes + resIntPart)/10),(curRes + resIntPart)%10)
} else {
res.unshift((curRes + resIntPart)%10)
resIntPart = Math.floor((curRes + resIntPart)/10)
}
}
return res.join("")
};
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
51
52
53
54
55
56
57
58
59
60
61
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
51
52
53
54
55
56
57
58
59
60
61
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/multiply-strings