给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式。

注意:不能使用任何内置的 BigInteger 库或直接将输入转换为整数。

思路

  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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
var multiply = function (num1, num2) {
if (num1 === '0' || num2 === '0') {
return '0'
}
const items1 = num1
.split('')
.reverse()
.map((item) => Number(item))
const items2 = num2
.split('')
.reverse()
.map((item) => Number(item))
let sumItems = [0]
const calcSum = (factor1, factor2) => {
let inc = 0
let cur = 0
const sumItems = []
while (cur < factor1.length || cur < factor2.length || inc) {
let sumVal = inc
if (cur < factor1.length) {
sumVal += factor1[cur]
}
if (cur < factor2.length) {
sumVal += factor2[cur]
}
sumItems.push(sumVal % 10)
inc = Math.floor(sumVal / 10)
++cur
}
return sumItems
}
for (let i = 0; i < items1.length; ++i) {
const val1 = items1[i]
let factor = new Array(i).fill(0)
let inc = 0
for (let j = 0; j < items2.length; ++j) {
const val = val1 * items2[j] + inc
inc = Math.floor(val / 10)
factor.push(val % 10)
}
if (inc > 0) {
factor.push(inc)
}
sumItems = calcSum(sumItems, factor)
}
return sumItems.reverse().join('')
}