大数相加
// 思路:
// 1. 以0补齐两个字符串,保证长度一致
// 2. 存储进位信息,每次相加加上他
// 3. 存储下一次进位信息
// 4. 算出对应位数相加取余数,加到字符串上
function addBigNum(s1,s2) {
let num = Math.max(s1.length,s2.length);
s1 = s1.padStart(num,0);
s2 = s2.padStart(num,0);
// 存储进位信息
let c = 0;
let res = '';
for(let i = num -1;i>=0;i--) {
let g = parseInt(s1[i]) + parseInt(s2[i]) + c;
c = Math.floor(g / 10);
g = g % 10;
res = g + res;
}
if(c === 1) {
res = 1 + res;
}
return res;
}
let s1 = '11111',s2 = '912222';
console.log(addBigNum(s1,s2))
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
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
编辑 (opens new window)
上次更新: 2022/09/18, 15:06:58