In Level 1, we explored the light switch analogy. Now let's implement real binary addition in code. We'll work with binary strings (like "1011" and "110") and produce their sum.
The Add Binary Algorithm
The classic "Add Binary" problem asks us to add two binary strings and return the result as a binary string. Here's the approach:
- Start from the rightmost characters of both strings
- Add corresponding digits along with any carry:
- Convert each char to int (e.g., '1' → 1)
- Sum = digit_a + digit_b + carry
- Calculate the result digit:
sum % 2 (0 or 1)
- Calculate the new carry:
sum // 2 (0 or 1)
- Append result digit and continue
- After the loop, reverse the result (we built it backwards)
Python Implementation
def addBinary(a: str, b: str) -> str:
i, j = len(a) - 1, len(b) - 1
carry = 0
result = []
while i >= 0 or j >= 0 or carry:
total = carry
if i >= 0:
total += int(a[i]) # Add digit from string a
i -= 1
if j >= 0:
total += int(b[j]) # Add digit from string b
j -= 1
result.append(str(total % 2)) # Current bit
carry = total // 2 # New carry
return ''.join(reversed(result))
Key points:
- We build the result in reverse order, then reverse at the end
- The loop continues while there are digits OR a carry remaining
- Using a list and
join() is more efficient than string concatenation
Java Implementation
public String addBinary(String a, String b) {
StringBuilder result = new StringBuilder();
int i = a.length() - 1, j = b.length() - 1;
int carry = 0;
while (i >= 0 || j >= 0 || carry > 0) {
int total = carry;
if (i >= 0) {
total += a.charAt(i--) - '0'; // Convert char to int
}
if (j >= 0) {
total += b.charAt(j--) - '0';
}
result.append(total % 2);
carry = total / 2;
}
return result.reverse().toString();
}
Key points:
charAt(i) - '0' converts char '0' or '1' to int 0 or 1
StringBuilder is efficient for building strings
reverse() method reverses in-place
C++ Implementation
string addBinary(string a, string b) {
string result = "";
int i = a.size() - 1, j = b.size() - 1;
int carry = 0;
while (i >= 0 || j >= 0 || carry) {
int total = carry;
if (i >= 0) {
total += a[i--] - '0';
}
if (j >= 0) {
total += b[j--] - '0';
}
result += to_string(total % 2);
carry = total / 2;
}
reverse(result.begin(), result.end());
return result;
}
Key points:
- Uses
reverse() from the <algorithm> header
to_string() converts int to string
- Same algorithm, different syntax
Understanding the Math
Why do total % 2 and total / 2 work? Let's trace through:
| Total |
Binary Meaning |
total % 2 |
total / 2 |
| 0 |
0 + 0 + 0 |
0 |
0 |
| 1 |
0 + 1 + 0 or 1 + 0 + 0 |
1 |
0 |
| 2 |
1 + 1 + 0 |
0 |
1 |
| 3 |
1 + 1 + 1 |
1 |
1 |
Pattern: The modulo operation gives us the current bit (even/odd), and integer division gives us the carry.
Common Pitfalls and Solutions
❌ Pitfall 1: Forgetting the Final Carry
Problem: Loop ends when strings are exhausted, but a carry remains.
# BAD: Loop doesn't handle remaining carry
while i >= 0 or j >= 0: # Missing "or carry"!
Solution: Include or carry in the loop condition.
❌ Pitfall 2: Not Handling Different Lengths
Problem: Accessing index out of bounds when one string is shorter.
# BAD: Assumes both strings have same length
total += int(a[i]) + int(b[j]) # Crash if one is exhausted!
Solution: Check index bounds before accessing each string.
❌ Pitfall 3: String Concatenation in Loop
Problem: Building strings with += is O(n²) in many languages.
# BAD: Inefficient
result = ""
for bit in bits:
result = bit + result # Creates new string each time!
Solution: Use a list/array and reverse at the end.
Alternative Approaches
1. Built-in Conversion (Python)
# Simple but limited by integer size
def addBinary(a, b):
return bin(int(a, 2) + int(b, 2))[2:]
Warning: This fails for very long binary strings that exceed integer limits. The string-based approach handles arbitrarily long inputs.
2. Bit Manipulation
# Using XOR for sum, AND for carry
def addBinary(a, b):
x, y = int(a, 2), int(b, 2)
while y:
x, y = x ^ y, (x & y) << 1
return bin(x)[2:]
This uses bitwise operations: XOR adds without carry, AND finds carry positions, shift moves carry left.
Complexity Analysis
Time Complexity
- O(max(n, m)) where n, m are string lengths
- We traverse each string once
- The final reverse is O(max(n, m))
Space Complexity
- O(max(n, m)) for the result string
- Result can be at most max(n, m) + 1 characters
- No additional data structures needed