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

在 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));

猜你喜欢

转载自blog.csdn.net/weixin_43972437/article/details/114033607