两个无穷大的数相加

思路:先将两个无穷大的数分割:

 1 // 分割无穷大数
 2 function numberSlice(str, len, array) {
 3     let arr = array || []
 4     let number = len || 10
 5     arr.push(str.slice((str.length - number), str.length))
 6     str = str.slice(0, str.length - number)
 7     if (str.length > number){
 8         numberSlice(str, number, arr)
 9     } else {
10         array.push(str)
11     }
12     return arr
13 }

再进行相加:

 1 // 两个无穷大的数相加
 2 function numberAdd(a, b, len) {
 3     let arr1 = numberSlice(a, len)
 4     let arr2 = numberSlice(b, len),totalArr = []
 5     let length = arr1.length > arr2.length ? arr1.length : arr2.length
 6     for (let i = 0; i < length; i++ ){
 7         totalArr.push((parseInt(arr1[i]) || 0) + (parseInt(arr2[i]) || 0))
 8     }
 9     for (let j = 0; j < totalArr.length; j++) {
10         if (totalArr[j].toString().length > len) {
11             let nowStr = totalArr[j].toString()
12             totalArr[j] = nowStr.slice(len)
13             totalArr[j +1] = parseInt(totalArr[j +1]) + parseInt((nowStr.slice(0,len)))
14         }
15     }
16     totalArr = totalArr.reverse()
17     return totalArr.join('')
18 }

测试:

let result = numberAdd('15524', '5524', 1)
console.log(result)
console.log('15524+5524', 15524+5524)

 

猜你喜欢

转载自www.cnblogs.com/StruggleStudyhard/p/8946506.html