Add Binary
Difficulty: Easy · Pattern: Bit Manipulation · LeetCode #67
Given two binary strings a and b, return their sum as a binary string.
Examples
text
a = "11", b = "1" → "100"
a = "1010", b = "1011" → "10101"Hints
- Add from the least significant end, as on paper, keeping a carry.
- The strings can be thousands of bits long, so converting to an integer won't work in most languages.
Approach
Two pointers from the right: s = carry + digit(a) + digit(b), output s % 2, carry s // 2. Continue while there are digits left or the carry is 1, then reverse the collected bits. O(max(m, n)).
The same template solves Add Strings (base 10) and Add Two Numbers (linked lists).
Complexity
Time: O(max(m, n)). Space: O(max(m, n)).
Python solution
def addBinary(a, b):
i, j, carry, out = len(a) - 1, len(b) - 1, 0, []
while i >= 0 or j >= 0 or carry:
s = carry
if i >= 0:
s += int(a[i]); i -= 1
if j >= 0:
s += int(b[j]); j -= 1
out.append(str(s & 1))
carry = s >> 1
return ''.join(reversed(out))JavaScript solution
function addBinary(a, b) {
let i = a.length - 1, j = b.length - 1, carry = 0, out = '';
while (i >= 0 || j >= 0 || carry) {
let s = carry;
if (i >= 0) s += a.charCodeAt(i--) - 48;
if (j >= 0) s += b.charCodeAt(j--) - 48;
out = (s & 1) + out;
carry = s >> 1;
}
return out;
}