Search code examples
javascriptalgorithmmultiplication

Multiply strings


Problem Set- Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.

My algorithm seems to work fine for all but one test case of palindrome from 1-9

UPDATE

Javascript has a parse method but I don't want to use that as the problem is from leetcode or a matter of fact from any such site and the problem sets says that explicitly.

//**Input:**
var n1 = "123456789"
var n2 = "987654321"

var multiply = function(str1, str2) {
  var sum = 0, k = 1;
  for( var i = str1.length - 1; i>=0; i--){
      var val1 = parseInt(str1[i], 10) * k;

      k *= 10;
      var d = 1;
      for(var j = str2.length - 1; j >=0; j--){
          var val2 = parseInt(str2[j], 10) * d;
          d *= 10;

          sum +=  val1 * val2;

      }
  }
  return sum.toString();
};

console.log(multiply(n1,n2))

I cannot understand what's going wrong. Other palindromes work fine though.


Solution

  • The purpose of such an exercise is probably that you implement your own multiplication algorithm for big numbers. When an integer (the product in this case) needs more than 15-16 digits, JavaScript number type cannot store that with enough precision, and so the outcome will be wrong if you just use the multiplication operator on the inputs.

    Even if you sum up smaller products in a number variable, that sum will eventually cross the limit of Number.MAX_SAFE_INTEGER. You need to store the result of smaller calculations in another data structure, like an array or a string.

    Here is a simple implementation of the long multiplication algorithm:

    function multiply(a, b) {
        const product = Array(a.length+b.length).fill(0);
        for (let i = a.length; i--; null) {
            let carry = 0;
            for (let j = b.length; j--; null) {
                product[1+i+j] += carry + a[i]*b[j];
                carry = Math.floor(product[1+i+j] / 10);
                product[1+i+j] = product[1+i+j] % 10;
            }
            product[i] += carry;
        }
        return product.join("").replace(/^0*(\d)/, "$1");
    }
    
    console.log(multiply("123456789", "987654321"));

    Since ECMAScript 2020, JavaScript has the bigint data type, with which you can do such multiplications out of the box (note the n suffix):

    console.log((123456789n * 987654321n).toString());

    NB: In a browser you don't need to call toString() explicitly, but the above Stack Snippet console implementation is limited, so it needs it.