大整数加法

作者: sullay | 来源:发表于2019-12-26 14:21 被阅读0次
    /**
     * 腾讯笔试: 大整数加法
     *
     * 实现大整数相加算法,两个数用字符串模拟函数原型:
     * function add(a, b) {}
     * @param {string} a
     * @param {string} b 
     * @return {string} - a b 之和
     * 
     * 测试用例如下:
     * 用例1: console.log(add('999', '1') === '1000');
     * 用例2: console.log(add('1', '999') === '1000');
     * 用例3: console.log(add('123', '123') === '246');
     * 用例4: console.log(add('999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999', '1')==='1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000')
     */
    
    function add(a, b) {
      let res = ""
      let c = 0
      a = a.split('')
      b = b.split('')
      while (a.length > 0 || b.length > 0 || c > 0) {
        c = ~~a.pop() + ~~b.pop() + c
        res = c % 10 + res
        c >= 10 ? c = 1 : c = 0
      }
      return res.replace(/^0+/, '')
    }
    console.log(add('00999', '1') === '1000');
    console.log(add('1', '999') === '1000');
    console.log(add('123', '123') === '246');
    console.log(add('999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999', '1') === '1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000')
    

    相关文章

      网友评论

        本文标题:大整数加法

        本文链接:https://www.haomeiwen.com/subject/ugnkoctx.html