du blog
Hello, welcome to my blog
两个非负大整数相加
created: Jun 14 21updated: Jun 14 21

题目:两个非负大整数相加

解法1:在js中使用BigInt类型

解法2:

1const numLength = 15; 2 3function bigNumSum(bigNumA:string, bigNumB:string){ 4 let resultA:Array<string> = []; 5 let resultB:Array<string> = []; 6 let result:Array<string> = [] 7 let bigResult = bigNumA.length > bigNumB.length ? resultA :resultB; 8 for (let index = bigNumA.length; index > 0; index-=numLength) { 9 let start = index - numLength; 10 start = start >=0 ? start : 0; 11 resultA.push(bigNumA.substring(start, index)); 12 } 13 for (let index = bigNumB.length; index > 0; index-=numLength) { 14 let start = index - numLength; 15 start = start >=0 ? start : 0; 16 resultB.push(bigNumB.substring(start, index)); 17 } 18 let bigLocation:string = '0'; 19 bigResult.forEach((_, index)=> { 20 let a:number = resultA[index]? Number(resultA[index]) : 0; 21 let b:number = resultB[index]? Number(resultB[index]) : 0; 22 let itemResult:string = String(a + b + Number(bigLocation)); 23 if(itemResult.length > numLength) { 24 bigLocation = itemResult[0]; 25 itemResult = itemResult.substring(1); 26 } else { 27 if(index !== bigResult.length -1 ){ 28 itemResult = itemResult.padStart(numLength, '0') 29 } 30 bigLocation = '0' 31 } 32 result.unshift(itemResult) 33 }) 34 bigLocation !== '0' &amp;&amp; result.unshift(bigLocation) 35 return result.join('') 36} 37

思路:

1. js中数字的最大精度范围为 Math.pow(2, 53) - 1 即 16 位,则设置分割长度 为 15位

2. 遍历原始数字从低位开始遍历,15位为一个元素 放入数组中

3. 挑选长度最大的数组遍历,下标相同的元素相加,设置进位变量,存储进位数值,相加后的结果放入结果数组