js 实现大整数加法

2019-05-08  本文已影响0人  忍不住的k

问题描述
实现‘字符串加法’,即将两个以字符串形式表示的数字相加,得到结果然后返回一个新的字符串。

例如:输入‘123’,‘321’,返回‘444’

这样在进行两个任意大的整数相加的时候,既不会溢出,也不会损失精度。

function sumStrings(a,b){
    var res='', c=0;
    a = a.split('');
    b = b.split('');
    console.log(a);
    console.log(b);
    while (a.length || b.length || c){
        c += ~~a.pop() + ~~b.pop();
        res = c % 10 + res;//转成字符串
        //console.log(res);
        c = c>9;//大于9进位
    }
    return res.replace(/^0+/,'');
}
  console.log(sumStrings('37486040775460377773700','7669000000000000000000000000000'))
上一篇 下一篇

猜你喜欢

热点阅读