实现大数相加

文章链接

      const a = 9007199254740991n
      const b = 1234567899999999999n
      console.log(a + b)

      const strA = '9007199254740991'
      const strB = '1234567899999999999'

      const add = function (a, b) {
        const maxLen = Math.max(a.length, b.length)
        a = a.padStart(maxLen, 0)
        b = b.padStart(maxLen, 0)

        let current = 0 // 个位/当前计算位
        let next = 0 // 进位
        let sum = '' // 结果

        for (let i = maxLen - 1; i >= 0; i--) {
          current = parseInt(a[i]) + parseInt(b[i]) + next
          next = Math.floor(current / 10)
          sum = (current % 10) + sum
        }
        if (next === 1) {
          sum = '1' + sum
        }

        return sum
      }

      console.log(add(strA, strB))