让前端飞Web前端之路

大整数加法

2019-12-26  本文已影响0人  sullay
/**
 * 腾讯笔试: 大整数加法
 *
 * 实现大整数相加算法,两个数用字符串模拟函数原型:
 * function add(a, b) {}
 * @param {string} a
 * @param {string} b 
 * @return {string} - a b 之和
 * 
 * 测试用例如下:
 * 用例1: console.log(add('999', '1') === '1000');
 * 用例2: console.log(add('1', '999') === '1000');
 * 用例3: console.log(add('123', '123') === '246');
 * 用例4: console.log(add('999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999', '1')==='1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000')
 */

function add(a, b) {
  let res = ""
  let c = 0
  a = a.split('')
  b = b.split('')
  while (a.length > 0 || b.length > 0 || c > 0) {
    c = ~~a.pop() + ~~b.pop() + c
    res = c % 10 + res
    c >= 10 ? c = 1 : c = 0
  }
  return res.replace(/^0+/, '')
}
console.log(add('00999', '1') === '1000');
console.log(add('1', '999') === '1000');
console.log(add('123', '123') === '246');
console.log(add('999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999', '1') === '1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000')
上一篇下一篇

猜你喜欢

热点阅读