跳到主要内容

大数相加解决

因为有js有数字大小限制,所以只能转成字符串一位一位的相加

function add(a, b) {
const arrA = a.split('').reverse();
const arrB = b.split('').reverse();
const result = [];

const type = (a) => {
if (a && !isNaN(Number(a))) {
return Number(a);
}
return 0;
}

let tem = 0;
for (let index = 0; index < Math.max(arrA.length, arrB.length); index++) {
const mm = type(arrA[index]);
const nn = type(arrB[index]);
const next = nn + mm + tem;
tem = next > 9 ? 1 : 0;
result.unshift(next % 10);
}
tem > 0 && result.unshift(1);
return result.join('');
}

console.log(add('9991111111', '9999999999999999999999'));
Loading Comments...