Multiply Strings Leetcode 43 question Correct Solution
Question :
Given two non-negative integers num1
and num2
represented as strings, return the product of num1
and num2
, also described as a string.
Note: You must not use any built-in BigInteger library or directly convert the inputs to integers.
Constraints:
1 <= num1.length, num2.length <= 200
num1
andnum2
consist of digits only.- Both
num1
andnum2
do not contain any leading zero, except the number0
itself.
/**
* @param {string} num1
* @param {string} num2
* @return {string}
*/
var add = function(a, b){
// length of a should be smaller
if(a.length > b.length)return add(b, a);
// iterate a
let i = a.length-1, j = b.length-1, carry = 0, currAns='';
while(i >= 0){
// get nums
let numA = a[i]-0;
let numB = b[j]-0;
// add numA and numB + carry
let sum = numA + numB + carry;
sum = '' + sum;
// add ones digit to currAns
currAns = (sum.length > 1) ? sum[1] + currAns : sum + currAns;
// take carry if any
carry = (sum.length > 1) ? 1 : 0;
// decrement i and j
i--;
j--;
}
// if b was large number i.e j != 0
while(j >= 0){
let numB = b[j]-0;
// add numB + carry
let sum = numB + carry;
sum = '' + sum;
// add ones digit to currAns
currAns = (sum.length > 1) ? sum[1] + currAns : sum + currAns;
// take carry if any
carry = (sum.length > 1) ? 1 : 0;
// decrement j
j--;
}
// check if there is a carry remaining to be settled
if(carry != 0){
currAns = '1' + currAns;
}
return currAns;
}
var sumOfArr = function(arr){
if(arr.length == 1)return arr[0];
// ans = sum of first two numbers;
let ans = add(arr[0], arr[1]+'0');
// start iterating from the third number;
let i = 2;
let zero = '0';
while(i < arr.length){
let b = arr[i]+zero.repeat(i)
ans = add(ans, b);
i++;
}
return ans;
}
var multiply = function(num1, num2) {
if(num2.length > num1.length)return multiply(num2, num1);
if(num1-0 === 0 || num2-0 === 0)return "0";
let i = num2.length-1;
// array to sum and get final ans
let sumArr = [];
// num1 * num2 = ans
// iterating num2 from ones place
while(i >= 0){
let currAns = '', carry = 0, ans;
// Convert num2 char to int
let num = num2[i]-0;
let j = num1.length-1;
// iterating num1 from ones place
while(j >= 0){
// convert num1 char to int
let n = num1[j]-0;
// (multiply num1 int to num2 int) + (carry if any) = ans
ans = (n*num) + carry;
// convert ans to string
ans = ''+ans;
// store ones digit of ans to currAns;
currAns = (ans.length > 1) ? ans[1] + currAns : ans[0] +currAns;
// store twos digit of ans (int) to carry if any;
carry = (ans.length > 1) ? ans[0]-0 : 0;
// if j == 0 And carry != 0 then push carry to the currAns;
if(j == 0 && carry != 0)currAns = '' + carry + currAns;
// decrement j
j--;
}
// push currAns to sumArr
sumArr.push(currAns);
// decrement i;
i--;
}
return sumOfArr(sumArr);
};
jjjjjjjJaavas
Ja
Ja
Comments
Post a Comment