Created
November 16, 2019 19:12
-
-
Save anxious-coder-lhs/5a178bf505ae4c39d74acf5cb6cba022 to your computer and use it in GitHub Desktop.
Integer Multiplication as strings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function multiply(first, second) { | |
if (first === "0" || second === "0") { | |
return "0"; | |
} | |
const maxLength = first.length + second.length; | |
const result = Array(maxLength).fill(0); | |
for (let i = second.length - 1; i >= 0; i--) { | |
let opIdx = maxLength - (second.length - i); | |
for (let j = first.length - 1; j >= 0; j--) { | |
const product = | |
result[opIdx] + parseInt(first.charAt(j)) * parseInt(second.charAt(i)); | |
result[opIdx] = Math.floor(product % 10); | |
result[opIdx - 1] = Math.floor(product / 10) + result[opIdx - 1]; | |
opIdx--; | |
} | |
} | |
return result[0] === 0 ? result.slice(1).join("") : result.join(""); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment