计算大数之和

作者:xie392地址:https://v.douyin.com/ie9WdJgN/更新时间:2024-12-21

案例代码

1
/**
2
* @description 计算大数之和
3
*
4
* @param {string} a
5
* @param {string} b
6
* @return {string}
7
* @example
8
* sum('111', '19') // '130'
9
*/
10
function sum(a, b) {
11
// 最大位数
12
const len = Math.max(a.length, b.length)
13
14
// 不够位数前面补0
15
a = a.padStart(len, '0') // 1 1 1
16
b = b.padStart(len, '0') // 0 1 9
17
18
// 进位
19
let carry = 0
20
// 结果
21
let result = ''
22
23
// 从后面往前遍历
24
for (let i = len - 1; i >= 0 ; i--) {
25
const sum = +a[i] + +b[i] + carry
26
// 字符不断累加
27
// i = 2, sum = 1 + 9 + 0 = 10, result = 10 % 10 + '' = '0', carry = 1
28
// i = 1, sum = 1 + 1 + 1 = 3, result = 3 % 10 + '0'= '30', carry = 0
29
// i = 0, sum = 1 + 0 + 0 = 1, result = 1 % 10 + '30' = '130', carry = 1
30
// 最终结果为 130
31
result = sum %10 + result
32
// 满 10 进 一
33
carry = Math.floor(sum / 10)
34
}
35
36
// 如果还有进位
37
if (carry > 0) {
38
result = carry + result
39
}
40
41
return result
42
}
43
44
console.log(sum('111','19'))
45
console.log(sum('111111111111111111111119999', '911111111111111111111191111'))

输出结果:

1
130
2
1022222222222222222222311110