zl程序教程

您现在的位置是:首页 >  后端

当前栏目

算法:实现两个大数字相加

算法 实现 数字 两个 相加
2023-09-27 14:27:10 时间

在 js 中,过大的数字会导致精度丢失从而出现问题,比如:
在这里插入图片描述
那么如何实现两个大数字相加呢?

const a = '123456789';
const b = '11111111111111111111111111';
 
function add(a, b) {
    var temp = 0;
    var res = ""
    a = a.split("");
    b = b.split("");
    while (a.length || b.length || temp) {
        temp += ~~(a.pop()) + ~~(b.pop());
        res = (temp % 10) + res;
        temp = temp > 9
    }
    return res
}
 
console.log(add(a, b));