i was doing following leetcode question on multiplying strings: https://leetcode.com/problems/multiply-strings/
(我在做关于字符串相乘的leetcode问题: https ://leetcode.com/problems/multiply-strings/)
The question is
(问题是)
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.
(给定两个非负整数num1和num2表示为字符串,返回num1和num2的乘积,也表示为字符串。)
Example 1:
(范例1:)
Input: num1 = "2", num2 = "3"
Output: "6"
Example 2:
Input: num1 = "123", num2 = "456"
Output: "56088"
Note:
(注意:)
The length of both num1 and num2 is < 110. Both num1 and num2 contain
(num1和num2的长度均小于110。num1和num2均包含)
only digits 0-9.
(仅数字0-9。)
Both num1 and num2 do not contain any leading zero, (num1和num2都不包含任何前导零,)
except the number 0 itself.
(除了数字0本身。)
You must not use any built-in BigInteger (您不得使用任何内置的BigInteger)
library or convert the inputs to integer directly.
(库或将输入直接转换为整数。)
For this used the following approach 1. Convert the string to int 2. Multiply the int
(为此,使用以下方法:1.将字符串转换为int 2.将int乘以)
Algo for the same is
(同样的算法是)
const numberMap = {
"0": 0,
"1": 1,
"2": 2,
"3": 3,
"4": 4,
"5": 5,
"6": 6,
"7": 7,
"8": 8,
"9": 9
}
var multiply = function(num1, num2) {
let i = num1.length
let j = num2.length
let sum = currentPower = 0
let firstNumber = secondNumber = 0
while(i > 0 || j > 0) {
// if I or J is equal to zero, means we have itterated hence we will set the value to one
const firstNum = i > 0 ? (numberMap[num1[i-1]]) * (10**currentPower) : 0
const secondNum = j > 0 ? (numberMap[num2[j-1]]) * (10**currentPower) : 0
firstNumber += firstNum
secondNumber += secondNum
currentPower++
i--
j--
}
sum = firstNumber * secondNumber
return sum.toString()
};
but when the following input is given
(但是当给出以下输入时)
"123456789"
"987654321"
it yields the following output "121932631112635260"
instead of "121932631112635269"
(它产生以下输出"121932631112635260"
而不是"121932631112635269"
)
Any idea how I can fix this?
(知道我该如何解决吗?)
ask by anny123 translate from so 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…