LeetCode: Multiply Strings Solution
Will make this better. Word promised!Approach
Apply this (I don't know what this is called in English so please comment if you know)
1(a + b) * (c + d) = a * c + a * d + b * c + b * d
Example
1123 * 45623123 = 100 + 20 + 34456 = 400 + 50 + 656123 * 456 = (100 + 20 + 3) * (400 + 50 + 6)
For sum, we will use solution from LeetCode 415 Add Strings
For multiplication of numbers like 10 200 3000, etc. Yes we will not use normal multiplication with BigInt since this would violate the problem's rules. Instead, we will do the multiplication for the digit, and add up the rest zeros
Example
1300 * 4000023300: digit 3, 2 0s440000: digit 4, 4 0s56300 * 40000 = 3 * 4 + (2 + 4)0s = 12 plus '000000' = 12000000
Implementation
1// this is from LeetCode 415 Add Strings2var addStrings = function (num1, num2) {3 const maxLength = Math.max(num1.length, num2.length)4 num1 = num1.padStart(maxLength, "0").split("").reverse()5 num2 = num2.padStart(maxLength, "0").split("").reverse()67 const res = []8 let carry = 0910 for (let i = 0; i < maxLength; i++) {11 const digitSum = Number(num1[i]) + Number(num2[i]) + carry12 res.push(digitSum % 10)13 carry = Math.floor(digitSum / 10)14 }1516 carry && res.push(carry)1718 return res.reverse().join("")19}2021const splitToDigitAndZeros = num => {22 const n = num.length23 return num.split("").map((digit, i) => [digit, n - i - 1])24}2526var multiply = function (num1, num2) {27 num1 = splitToDigitAndZeros(num1)28 num2 = splitToDigitAndZeros(num2)2930 let res = "0"3132 for (const [digit1, numberOfZeros1] of num1) {33 for (const [digit2, numberOfZeros2] of num2) {34 let temp = String(digit1 * digit2)35 if (temp > 0) temp += "0".repeat(numberOfZeros1 + numberOfZeros2)3637 res = addStrings(res, temp)38 }39 }4041 return String(res)42}
References
Similar problems
Apply Discount to Prices
Comments
Loading comments...
Tags
leetcode
math
string
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.
Next Post
Add digits with carry
Previous Post
If I remember correctly, Alex K. also loves recursion