大数乘法和大数加法

Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 189

Author 回答者: shfshanyue

TODO

Author 回答者: haotie1990

var multiply = function (num1, num2) {
  if (num1 === "0" || num2 === "0") {
    return "0";
  }
  let num1s = num1.split("");
  let num2s = num2.split("");
  num1s.reverse();
  num2s.reverse();
 
  function add(a, b) {
    a = a.split("").reverse();
    b = b.split("").reverse();
    let len = Math.max(a.length, b.length);
    let c = 0;
    let r = [];
    for (let i = 0; i < len; i++) {
      let d = Number(a[i] || 0) + Number(b[i] || 0) + c;
      let e = 0;
      if (d >= 10) {
        e = d - 10;
        c = 1;
      } else {
        e = d;
        c = 0;
      }
      r[i] = e;
    }
    if (c === 1) {
      r[r.length] = 1;
    }
    return r.reverse().join("");
  }
  let results = [];
  for (let i = 0; i < num1s.length; i++) {
    for (let j = 0; j < num2s.length; j++) {
      let zero = Array.from({ length: i + j })
        .fill(0)
        .join("");
      results.push(Number(num1s[i]) * Number(num2s[j]) + zero);
    }
  }
  return results.reduce((acc, c) => {
    return add(acc, c);
  });
};