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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| const splitLen = 15; const add = (...rest) => { if (rest.length < 2) { return rest[0]; } const num = rest.pop(); return +add(...rest) + (+num) + ''; }; const zeros = new Array(splitLen).fill(0).join(''); const splitNum = (numStr) => { const numStrArr = numStr.split(''); const nums = []; while (numStrArr.length) { const item = numStrArr.splice(-splitLen); nums.push(item.join('')); } return nums; };
const classifyAdd = (n1Nums, n2Nums) => { let resNums = []; let carry = ''; while (n1Nums.length && n2Nums.length) { let part; const res = add(n1Nums.shift(), n2Nums.shift(), carry); if (res.length > splitLen) { part = res.slice(-splitLen); carry = res.slice(0, -splitLen); } else { part = zeros.slice(0, -res.length) + res; carry = ''; } resNums.push(part); } if (n1Nums.length) { const restNums = carry ? classifyAdd([carry], n1Nums) : n1Nums; resNums = [...resNums, ...restNums]; } if (n2Nums.length) { const restNums = carry ? classifyAdd([carry], n2Nums) : n2Nums; resNums = [...resNums, ...restNums]; } return resNums; }
function bigNumAdd(str1, str2) { if (str1.length < 16 && str2.length < 16) { return add(str1, str2); } const numArr1 = splitNum(str1); const numArr2 = splitNum(str2); const resNums = classifyAdd(numArr1, numArr2).reverse(); const resStr = resNums.join('').replace(/^0*/, ''); return resStr; }
function bigNumsAdd(...rest) { if (rest.length < 2) { return rest[0]; } const str1 = rest.shift(); return bigNumAdd(str1, bigNumsAdd(...rest)); } const str1 = '1111111111'; const str2 = '444'; const str3 = '00000000000000000000000000000000000000000000000000'; const resNums = bigNumsAdd(str1, str2, str3); console.log('resNums', resNums);
|