js-challenges icon indicating copy to clipboard operation
js-challenges copied to clipboard

二进制求和

Open Pcjmy opened this issue 2 years ago • 1 comments

Pcjmy avatar Feb 09 '23 06:02 Pcjmy

function getSum (a, b) {
  // 进位
  let curry = 0
  let maxLength = Math.max(a.length, b.length)
  a = a.padStart(maxLength, 0)
  b = b.padStart(maxLength, 0)
  let res = ''
  for (let i = maxLength - 1; i >= 0; i--) {
    let sum = parseInt(a[i]) + parseInt(b[i]) + curry
    curry = Math.floor(sum / 2)
    res = sum % 2 + res
  }
  // 处理最后一位有进位的情况
  if (curry === 1) {
    res = curry + res
  }
  return res
}

console.log(getSum('11', '10'))



topulikeweb avatar Mar 17 '24 12:03 topulikeweb