Algorithm: Realize the addition of two big numbers

In js, too large numbers will cause the loss of precision and cause problems, such as:
Insert picture description here
So how to add two large numbers?

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

Guess you like

Origin blog.csdn.net/weixin_43972437/article/details/114033607