计算大数之和
作者:xie392地址:https://v.douyin.com/ie9WdJgN/更新时间:2024-12-21
案例代码
1/**2* @description 计算大数之和3*4* @param {string} a5* @param {string} b6* @return {string}7* @example8* sum('111', '19') // '130'9*/10function sum(a, b) {11// 最大位数12const len = Math.max(a.length, b.length)1314// 不够位数前面补015a = a.padStart(len, '0') // 1 1 116b = b.padStart(len, '0') // 0 1 91718// 进位19let carry = 020// 结果21let result = ''2223// 从后面往前遍历24for (let i = len - 1; i >= 0 ; i--) {25const sum = +a[i] + +b[i] + carry26// 字符不断累加27// i = 2, sum = 1 + 9 + 0 = 10, result = 10 % 10 + '' = '0', carry = 128// i = 1, sum = 1 + 1 + 1 = 3, result = 3 % 10 + '0'= '30', carry = 029// i = 0, sum = 1 + 0 + 0 = 1, result = 1 % 10 + '30' = '130', carry = 130// 最终结果为 13031result = sum %10 + result32// 满 10 进 一33carry = Math.floor(sum / 10)34}3536// 如果还有进位37if (carry > 0) {38result = carry + result39}4041return result42}4344console.log(sum('111','19'))45console.log(sum('111111111111111111111119999', '911111111111111111111191111'))
输出结果:
113021022222222222222222222311110
目录