当有两个整数 a 和 b ,在通常情况下我们有“+”运算符对其进行相加运算:
let sum = a + b;
但是 JS 在存放整数的时候是有一个安全范围的,一旦数字超过这个范围便会损失精度。
我们不能拿精度损失的数字进行运行,因为运算结果一样是会损失精度的。
所以,我们要用字符串来表示数据!(不会丢失精度)
JS 中整数的最大安全范围可以查到是:9007199254740991
假如我们要进行 9007199254740991 + 1234567899999999999
function add(a ,b){
let mathLength = Math.max(a.length, b.length)
//用0去补齐长度
a = a.padStart(mathLength, 0)
b = b.padStart(mathLength, 0)
let t = 0
let f = 0 //"进位"
let sum = ""
for(let i = mathLength-1; i>=0; i--){
t = parseInt(a[i]) + parseInt(b[i]) + f;
f = Math.floor(t/10);
sum = t%10 + sum;
}
if(f === 1){
sum = "1" + sum;
}
return sum
}
console.log(add(a ,b))