面试(机试题复盘)——1.31

77 阅读1分钟

需求:传入两个20位超长字符串数字对两项进行求和,不能使用js的BigInt

思路:将字符串先分割为字符串然后从后往前加,利用数组的pop从后删除(出栈)

         var a = '12345678901234567890'
         var b = '20232023202320232023'
         function sum(a,b) {
             let res = '' //保存最终结果 
             let c = 0 //保存两位相加的结果以及是否进位
             a = a.split('')
             b = b.split('')
             while (a.length || b.length || c) {
                 c+= parseInt(a.pop()) + parseInt(b.pop())
                 res = c % 10 + res
                 c>=10 // 保存进位
             }
         }
         return res