const add = (a, b) => {
// 反序
const arr1 = a.split('').reverse();
const arr2 = b.split('').reverse();
const length = Math.max(arr1.length, arr2.length);
const res = new Array(length + 1).fill(0);
res.forEach((item, index) => {
if (index === length) {
return;
}
// 防止undefined
const sum = Number(arr1[index] || 0) + Number(arr2[index] || 0);
// 进位
if (res[index] + sum > 9) {
res[index + 1] += 1;
res[index] = res[index] + sum - 10;
} else {
res[index] += sum;
}
});
// 第一位是0的话要去掉
if (Number(res[length]) === 0) {
res.pop();
}
// 反序回来
return res.reverse().join('');
}
console.log(add('426709752318', '95481253129')); // 522191005447