Skip to main content

Add Binary

Problem

Given two binary strings a and b, return their sum as a binary string.

 

Example 1:

Input: a = "11", b = "1"
Output: "100"

Example 2:

Input: a = "1010", b = "1011"
Output: "10101"

 

Constraints:

  • 1 <= a.length, b.length <= 104
  • a and b consist only of '0' or '1' characters.
  • Each string does not contain leading zeros except for the zero itself.

Solution

/**
* @param {string} a
* @param {string} b
* @return {string}
*/
var addBinary = function(a, b) {
let i = a.length - 1;
let j = b.length - 1;
let res = "";
let sum = 0;

while (i >= 0 || j >= 0) {
const bitA = a[i--] ?? "0";
const bitB = b[j--] ?? "0";

sum += bitA.charCodeAt() - "0".charCodeAt();
sum += bitB.charCodeAt() - "0".charCodeAt();

res = `${sum % 2}${res}`;
sum >>= 1;
}

if (sum) {
res = "1" + res;
}
return res;
};

We add digits of a and b one by one starting from the LSB. We use sum to track the sum of the current bit in a, b, and the carryover. Since we are working in base two, the current digit would be sum % 2 (ie. the remainder), and the carryover would be sum >> 1 (ie. the quotient).