Add Binary

Schoolbook binary addition with carry — walk both strings from the right.

Easy
Time O(max(m, n)) Space O(max(m, n))
LeetCode
4 min read
math string bit-manipulation

Problem#

Add two binary strings and return the binary sum as a string.

Examples#

  • "11", "1""100".
  • "1010", "1011""10101".

Constraints#

  • 1 <= a.length, b.length <= 10^4.

Approach#

Two pointers from the right with carry. Append (sum % 2) to result; carry is sum / 2. Reverse at the end.

Solution#

Add Binary
class Solution {
public:
string addBinary(string a, string b) {
int i = a.size() - 1, j = b.size() - 1, carry = 0;
string out;
while (i >= 0 || j >= 0 || carry) {
int x = (i >= 0) ? a[i--] - '0' : 0;
int y = (j >= 0) ? b[j--] - '0' : 0;
int s = x + y + carry;
out.push_back('0' + s % 2);
carry = s / 2;
}
reverse(out.begin(), out.end());
return out;
}
};

Editorial#

Identical structure to decimal addition, but with base 2. Each digit’s sum is at most 3 (1+1+1), producing digit 1 and carry 1 — the loop condition handles arbitrary trailing carry.

Complexity#

  • Time: O(max(m, n)).
  • Space: O(max(m, n)).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.