Skip to problem
←

Add Binary

Easy 0 attempts

You're given two strings a and b that represent numbers in binary (base 2). Add them together and return the result, also written as a binary string.

Function contract

Implement addBinary(a, b), where a and b are non-empty binary strings.

Output: The sum as a binary string with no leading zeros, except for "0".

Example 1

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

Example 2

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

Example 3

Input
a = "0"
b = "0"
Output
"0"
Constraints
  • 1 <= a.length, b.length <= 10^4
  • a and b consist only of 0 or 1
  • No leading zeros except 0 itself
Topics

Bit-by-Bit Addition

Traverse both strings from right to left, adding corresponding digits along with any carry.

javascript
function addBinary(a, b) {
  let i = a.length - 1, j = b.length - 1, carry = 0, result = [];
  while (i >= 0 || j >= 0 || carry) {
    let sum = carry;
    if (i >= 0) sum += parseInt(a[i--]);
    if (j >= 0) sum += parseInt(b[j--]);
    result.push(String(sum % 2));
    carry = Math.floor(sum / 2);
  }
  return result.reverse().join('');
}

Time: O(max(m, n)) | Space: O(max(m, n))

Loading discussion…

Saved in this browser only. Private to you.

JavaScript