面试题——超大正整数相加

在js中有最大的安全正整数,超过会导致精度丢失

当然我们可以使用BigInt,但是当我们面试时肯定不会让我们使用BigInt,这是需要我们自己写一个方法

function sum(a, b){
  //定义返回结果
  let result = ''
  //取出两个正整数的最大长度
  const len = Math.max(a.length, b.length)
  //不够最大长度的补前面补0
  a = a.padStart(len, '0')
  b = b.padStart(len, '0')
  //定义一个进位变量
  let carry = 0
  for (let i = len - 1; i >= 0; i--) {
    //循环字符串从后往前加,还得加上进位
    const n = +a[i] + +b[i] + carry
    //进位向下取整
    carry = Math.floor(n / 10)
    //往结果字符串的前面填值:(n % 10) = 5, result = '321'则:result = 5 + '321'
    result = (n % 10) + result
  }
  //如果两个位数相同有进位的数字前面加上进位的数
  if (carry){
    result = carry + result
  }
  //返回结果
  return result
}
console.log(sum('65161516112316466994113351', '15494964466811665931113548'))
文章目录