极客时间返利平台,你可以在上边通过山月的链接购买课程,并添加我的微信 (shanyue94) 领取返现。
每天晚上九点 B站讲解前端工程化直播,并解答相关问题。

# 大数乘法和大数加法

Issue

欢迎在 Gtihub Issue 中回答此问题: Issue 189 (opens new window)

TODO

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);
  });
};
Last Updated: 11/27/2021, 10:11:48 AM