Skip to content

Instantly share code, notes, and snippets.

@anxious-coder-lhs
Created November 16, 2019 19:12
Show Gist options
  • Save anxious-coder-lhs/5a178bf505ae4c39d74acf5cb6cba022 to your computer and use it in GitHub Desktop.
Save anxious-coder-lhs/5a178bf505ae4c39d74acf5cb6cba022 to your computer and use it in GitHub Desktop.
Integer Multiplication as strings
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