js中的超过16位数字相加问题
方案一
1 function sub(str1, str2) { 2 // 补全0,并多补一位0 3 let arr1 = null, 4 arr2 = null 5 if (str1.length > str2.length) { 6 str1 = '0' + str1 7 for (let i = str2.length; i < str1.length; i++) { 8 str2 = '0' + str2 9 } 10 arr1 = str1.split('') 11 arr2 = str2.split('') 12 } else { 13 str2 = '0' + str2 14 for (let i = str1.length; i < str2.length; i++) { 15 str1 = '0' + str1 16 } 17 arr1 = str1.split('') 18 arr2 = str2.split('') 19 } 20 // 注意这里arr里边保存的还是字符串,需要转成数字后再相加 21 for (let i = arr1.length - 1; i >= 0; i--) { 22 let temp = parseInt(arr1[i]) + parseInt(arr2[i]) 23 arr1[i] = temp % 10 24 // 处理得到进位的结果 25 arr1[i - 1] = parseInt(arr1[i - 1]) + Math.floor(temp / 10) 26 } 27 if (arr1[0] === 0) { 28 return (arr1.join('')).substring(1) 29 30 } else { 31 return arr1.join('') 32 } 33 }
方案二
1 function sub(a,b){ 2 var res='', c=0; 3 a = a.split(''); 4 b = b.split(''); 5 while (a.length || b.length || c){ 6 c += ~~a.pop() + ~~b.pop(); 7 res = c % 10 + res; 8 c = c>9; 9 } 10 return res.replace(/^0+/,''); 11 }
一条不甘于平凡的咸鱼分享