Add Binary Easy 0 attempts
LeetCode ↗

Add Binary

Easy MatrixBFSDFS LeetCode

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.

Input Format
Implement addBinary(a, b). Inputs below show JavaScript function arguments; there is no stdin parsing.
Output Format
Return the result described in the statement.

Sample Input and Output

Example 1 ยท Run Sample

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
Test Cases (3)
Case 1
Args: ["11","1"] Expected: "100"
Case 2
Args: ["1010","1011"] Expected: "10101"
Case 3
Args: ["0","0"] Expected: "0"
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 = (sum % 2) + result;
    carry = Math.floor(sum / 2);
  }
  return result;
}

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

Saved in this browser only. Private to you.

JavaScript