Skip to content
On this page

67.二进制求和

给你两个二进制字符串 a 和 b ,以二进制字符串的形式返回它们的和。

示例  1:
输入:a = "11", b = "1"
输出:"100"

示例  2:
输入:a = "1010", b = "1011"
输出:"10101"

提示:
1 <= a.length, b.length <= 104
a 和 b 仅由字符 '0' 或 '1' 组成
字符串如果不是 "0" ,就不含前导零

javascript
/**
 * @param {string} a
 * @param {string} b
 * @return {string}
 */
var addBinary = function (a, b) {
  var res = "",
    carry = 0
  if (a.length > b.length) {
    b = b.padStart(a.length, "0")
  } else {
    a = a.padStart(b.length, "0")
  }
  for (var i = a.length - 1; i >= 0; i--) {
    carry = carry + +a[i] + +b[i]
    res = (carry % 2) + res
    carry = carry >= 2 ? 1 : 0
  }
  if (carry === 1) {
    res = "1" + res
  }
  return res
}

console.log(addBinary("11", "1") === "100")
console.log(addBinary("1010", "1011") === "10101")