因为JavaScript的number有安全范围:[-2^53-1, 2^53]
,所以在大数相加的时候会出问题
比如
1 2 3
| let a = 9007199254740991; let b = 1234567899999999999; console.log(a+b);
|
可知,相加的结果是在整数范围内的,小于b,结果肯定不准确
实现思路
- 将大数转为字符串
- 对齐字符串
- 利用对齐位数相加并记录是否有进位
- 输出数字
代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| function sumBigInt(val1, val2) { let maxLen = Math.max(val1.length, val2.length); val1 = val1.padStart(maxLen, 0); val2 = val2.padStart(maxLen, 0); let remainer = 0; let digit = 0; let sum = ''; for (let index = maxLen - 1; index >= 0; index--) { remainer = parseInt(val1[index]) + parseInt(val2[index]) + digit; digit = Math.floor(remainer / 10); sum = remainer % 10 + sum; }
if (digit === 1) { sum = '1' + sum; }; return sum; }
let a = '9007199254740991'; let b = '1234567899999999999'; let res = sumBigInt(a, b); console.log(res);
|
参考
JS 实现两个大数相加?