Created
March 18, 2024 20:24
-
-
Save IAmAnubhavSaini/546f4a916f6a9cc5d2237740a357941a to your computer and use it in GitHub Desktop.
Big strings multiplication
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
/** | |
* @param {string} num1 | |
* @param {string} num2 | |
* @return {string} | |
*/ | |
var multiply = function(num1, num2) { | |
if(num1 === "0" || num2 === "0") { | |
return "0"; | |
} | |
const numbers = Array.from({length: num2.length}, _ => "0"); | |
for(let i = num2.length - 1; i >= 0; i--) { | |
numbers[i] = []; | |
for(let x = 0; x < num2.length - i - 1; x++) { | |
numbers[i].push("0"); | |
} | |
const m = Number(num2[i]); | |
let carry = "0"; | |
for(let j = num1.length - 1; j >= 0; j--) { | |
const n = Number(num1[j]); | |
const mn = (m * n) + Number(carry); | |
carry = (Math.floor(mn / 10)).toString(); | |
const nn = (mn%10).toString(); | |
console.log({m, n, mn, carry, nn}); | |
numbers[i].push(nn); | |
} | |
numbers[i].push(carry); | |
} | |
let sum = []; | |
let carry = 0; | |
for(let i = 0; i < num2.length + num1.length; i++) { | |
let s = 0; | |
for(let j = 0; j < numbers.length; j++) { | |
s += Number(numbers[j][i] || "0"); | |
} | |
s += carry; | |
carry = Math.floor(s/10); | |
s %= 10; | |
sum[i] = s; | |
} | |
console.log(numbers, sum); | |
if(sum[sum.length - 1] === 0) { | |
sum.pop(); | |
} | |
return sum.reverse().join(''); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment