silver-hands / sss

0 stars 0 forks source link

【Q076】😈第五部分:字符串😈67. 二进制求和 #76

Open fly0o0 opened 4 years ago

fly0o0 commented 4 years ago

67. 二进制求和

fly0o0 commented 4 years ago
/**
 * @param {string} a
 * @param {string} b
 * @return {string}
 */
var addBinary = function(a, b) {
  let ans = ''
  let carry = 0
  for (let i = a.length - 1, j = b.length - 1; i >= 0 || j >= 0; i--, j--) {
    let sum = carry

    sum += i >= 0 ? parseInt(a[i], 10) : 0

    sum += j >= 0 ? parseInt(b[j], 10) : 0

    ans = sum % 2 + ans

    carry = Math.floor(sum / 2)
  }

  if (carry == 1) {
    ans = carry + ans
  }

  return ans
};