Multiply Strings
Description
Given two non-negative integers num1
and num2
represented as strings, return the product of num1
and num2
, also represented as a string.
Example 1:
Input: num1 = "2", num2 = "3" Output: "6"
Example 2:
Input: num1 = "123", num2 = "456" Output: "56088"
Note:
- The length of both
num1
andnum2
is < 110. - Both
num1
andnum2
contain only digits0-9
. - Both
num1
andnum2
do not contain any leading zero, except the number 0 itself. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
Solution(javascript)
const addStrings = (num1, num2) => {
const reversedNum1 = num1.split('').reverse()
const reversedNum2 = num2.split('').reverse()
const { shorter, longer } = reversedNum1.length < reversedNum2.length
? { shorter: reversedNum1, longer: reversedNum2 }
: { shorter: reversedNum2, longer: reversedNum1 }
let rem = 0
let result = longer.reduce((acc, digit1, index) => {
const total = parseInt(digit1, 10) + (parseInt(shorter[index], 10) || 0) + rem
if (total >= 10) {
rem = 1
} else {
rem = 0
}
return [
...acc,
total >= 10 ? total - 10 : total,
]
}, [])
result = rem === 1 ? [...result, rem] : result
return result.reverse().join('')
}
const zero = (count) => {
let result = ''
while (count >= 1) {
result += '0'
count -= 1
}
return result
}
const multiply = (num1 = '', num2 = '') => {
let result = 0
for (let i = num2.length - 1; i >= 0; i--) {
let current = ''
let base = 0
for (let j = num1.length - 1; j >= 0; j--) {
let currentResult = parseInt(num1[j], 10) * parseInt(num2[i], 10) + base
if (currentResult >= 10) {
base = Math.floor(currentResult / 10)
currentResult -= base * 10
} else {
base = 0
}
current = `${currentResult + current}`
}
if (base > 0) {
current = base + current
}
// 偷懒
result = addStrings(result || '0', current + zero(num2.length - 1 - i))
}
if (result.length > 0 && result[0] === '0') {
return '0'
}
return result
}