Categories
interview

Multiply Strings

/**
 * @param {string} num1
 * @param {string} num2
 * @return {string}
 */
var multiply = function(num1, num2) {
  num1 = num1.split('').reverse().join('');
  num2 = num2.split('').reverse().join('');
  var result = [];
  for (let i = 0; i < num1.length + num2.length; i++) {
    result[i] = 0;
  }

  for (let i = 0; i < num1.length; i++) {
    for (let j = 0; j < num2.length; j++) {
      result[i + j] += (num1.charAt(i) - '0') * (num2.charAt(j) - '0');
    }
  }

  var str = '';
  for (let i = 0; i < result.length; i++) {
    var curr = result[i] % 10;
    var carry = Math.floor(result[i] / 10);
    if (i < result.length - 1)
      result[i + 1] += carry;
    str = curr + str;
  }

  while (str.charAt(0) === '0' && str.length > 1) {
    var n = str.length;
    str = str.substring(1, n);
  }

  return str;
};

console.log(multiply('2', '3'));
// Ouput: "6"

// var multiply = function(num1, num2) {
//  num1 = parseInt(num1, 10);
//  num2 = parseInt(num2, 10);
//  return (num1*num2)+'';
// }

Demo