While working on the leetcode problem related to multiplication, I encountered an interesting issue.
Given two non-negative integers num1 and num2 represented as strings, the task is to return the
product of these two numbers, also in string form.
However, there is a constraint: We cannot utilize any built-in BigInteger library or directly convert the inputs into integers.
Example 1:
Input: num1 = "2", num2 = "3"
Output: "6"
Example 2:
Input: num1 = "123", num2 = "456"
Output: "56088"
Constraints:
- The lengths of num1 and num2 are between 1 and 200.
- Both num1 and num2 consist only of digits.
- Neither num1 nor num2 have any leading zeros, except for the number 0 itself.
To approach this problem, I followed these steps:
- Convert the strings to integers.
- Multiply the integers.
The algorithm used for this process is as follows:
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) {
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()
};
However, when testing with the input:
"123456789"
"987654321"
The output obtained was ""121932631112635260"
instead of ""121932631112635269"
". How can this be corrected?