Skip to content

Instantly share code, notes, and snippets.

@e-mihaylin
Created October 3, 2018 11:46
Show Gist options
  • Save e-mihaylin/0b91328e899db0eeeafedf070ee165ee to your computer and use it in GitHub Desktop.
Save e-mihaylin/0b91328e899db0eeeafedf070ee165ee to your computer and use it in GitHub Desktop.
const multiply = (a, b) => {
const stack = [];
a = a.split``.reverse();
b = b.split``.reverse();
for (let i = 0, la = a.length; i < la; i++) {
for (let j = 0, lb = b.length; j < lb; j++) {
const m = a[i] * b[j];
const s = stack[i + j];
stack[i + j] = s ? s + m : m;
}
}
for (let i = 0, l = stack.length; i < l; i++) {
const move = Math.floor(stack[i] / 10);
stack[i] = stack[i] % 10;
if (stack[i + 1]) stack[i + 1] += move;
else if (move > 0) stack[i + 1] = move;
}
return stack.reverse().join``.replace(/^(0(?!$))+/, '');
}
//https://www.codewars.com/kata/multiplying-numbers-as-strings/javascript
Copy link

ghost commented Aug 11, 2021

/not my intent solution/
function multiply(a, b) {
const stack = [];
a = a.split.reverse(); b = b.split.reverse();

for (let i = 0, la = a.length; i < la; i++) {
for (let j = 0, lb = b.length; j < lb; j++) {
const m = a[i] * b[j];
const s = stack[i + j];
stack[i + j] = s ? s + m : m;
}
}

for (let i = 0, l = stack.length; i < l; i++) {
const move = Math.floor(stack[i] / 10);
stack[i] = stack[i] % 10;
if (stack[i + 1]) stack[i + 1] += move;
else if (move > 0) stack[i + 1] = move;
}

return stack.reverse().join``.replace(/^(0(?!$))+/, '');
}

@boosting-my-adrenaline
Copy link

function multiply(a, b) {return (BigInt(a) * BigInt(b)).toString()}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment