Add Binary
EasyGiven two binary strings a
and b,
return their sum as a binary string.
Example
Example 1:
Input: a = "11", b = "1"
Output: "100"
Explanation: 11 (3) + 1 (1) = 100 (4)
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
Explanation: 1010 (10) + 1011 (11) = 10101 (21)
Explanation
The key to solving this problem is understanding binary addition with carry. We add from right to left (least significant bit to most significant), just like decimal addition.
Binary Addition Rules
When adding two binary digits with a possible carry:
0 + 0 = 0(carry 0)0 + 1 = 1(carry 0)1 + 1 = 0(carry 1)1 + 1 + 1 = 1(carry 1)
Algorithm Steps
- Start from the rightmost digits of both strings
- Add corresponding digits along with any carry from the previous addition
- Compute the sum bit (sum % 2) and new carry (sum // 2)
- Build the result string from right to left
- After processing all digits, if there's a remaining carry, add it to the front
The result is built in reverse order and then reversed at the end, or we can prepend each digit (less efficient but clearer).
Idea Map
Set i = len(a) - 1
Set j = len(b) - 1
Set carry = 0
While i >= 0 or j >= 0 or carry > 0:
sum = carry
Add a[i] if i >= 0
Add b[j] if j >= 0
result += str(sum % 2)
carry = sum // 2
Reverse result
Return result
Complexity Analysis
Time Complexity
O(max(n, m)) - We traverse both strings once, where n and m are the lengths of the input strings.
Space Complexity
O(max(n, m)) - We store the result string, which can be at most max(n, m) + 1 characters long.
Code
def addBinary(a: str, b: str) -> str:
Initializes the function `addBinary` which takes two binary strings `a` and `b` and returns their sum as a binary string.
i, j = len(a) - 1, len(b) - 1
Sets pointers `i` and `j` to the last indices of strings `a` and `b` respectively (rightmost characters).
carry = 0
Initializes `carry` to 0. This will store the overflow when adding two 1s (1 + 1 = 0 with carry 1).
result = []
Creates an empty list to store result digits. Using a list is more efficient than string concatenation.
while i >= 0 or j >= 0 or carry:
Continues while there are digits left in either string OR there's a carry remaining.
total = carry
Starts the sum with the carry from the previous iteration.
if i >= 0:
Checks if there are still digits left in string `a`.
total += int(a[i])
Adds the current digit of `a` to the total (converts char '0' or '1' to int 0 or 1).
i -= 1
Moves the pointer for `a` one position to the left.
if j >= 0:
Checks if there are still digits left in string `b`.
total += int(b[j])
Adds the current digit of `b` to the total.
j -= 1
Moves the pointer for `b` one position to the left.
result.append(str(total % 2))
Appends the current bit (total % 2) to result. This gives 0 for even totals, 1 for odd.
carry = total // 2
Updates carry: 1 if total >= 2, else 0. This is integer division.
return ''.join(reversed(result))
Reverses the result (we built it backwards) and joins into a string.
public String addBinary(String a, String b) {
Initializes the function `addBinary` which takes two binary strings and returns their sum.
StringBuilder result = new StringBuilder();
Creates a StringBuilder for efficient string building.
int i = a.length() - 1, j = b.length() - 1;
Sets pointers to the last indices of both strings.
int carry = 0;
Initializes carry to 0.
while (i >= 0 || j >= 0 || carry > 0) {
Continues while digits remain in either string OR there's a carry.
int total = carry;
Starts the sum with the carry from previous iteration.
if (i >= 0) total += a.charAt(i--) - '0';
Adds digit from `a` and decrements index. The `- '0'` converts char to int value.
if (j >= 0) total += b.charAt(j--) - '0';
Adds digit from `b` and decrements index.
result.append(total % 2);
Appends the current bit (0 or 1) to the result.
carry = total / 2;
Updates carry: 1 if total >= 2, else 0.
}
End of while loop.
return result.reverse().toString();
Reverses the result (built backwards) and converts to string.
}
End of the function.
string addBinary(string a, string b) {
Initializes the function `addBinary` which takes two binary strings and returns their sum.
string result = "";
Creates an empty string to store the result.
int i = a.size() - 1, j = b.size() - 1;
Sets pointers to the last indices of both strings.
int carry = 0;
Initializes carry to 0.
while (i >= 0 || j >= 0 || carry) {
Continues while digits remain in either string OR there's a carry.
int total = carry;
Starts the sum with the carry from previous iteration.
if (i >= 0) total += a[i--] - '0';
Adds digit from `a` and decrements index. The `- '0'` converts char to int value.
if (j >= 0) total += b[j--] - '0';
Adds digit from `b` and decrements index.
result += to_string(total % 2);
Appends the current bit (0 or 1) to the result.
carry = total / 2;
Updates carry: 1 if total >= 2, else 0.
}
End of while loop.
reverse(result.begin(), result.end());
Reverses the result string in-place (we built it backwards).
return result;
Returns the final binary sum string.
}
End of the function.
Edge Cases & Common Mistakes
Forgetting the final carry
After processing all digits, there might still be a carry left (e.g., "1" + "1" = "10"). Make sure your loop condition includes the carry.
Strings of different lengths
Handle cases where one string is shorter than the other. Only add digits from a string when its index is valid (>= 0).
Building result in reverse
Since we process from right to left but build the result left to right, we need to reverse at the end. Or prepend each digit (less efficient).
Empty strings
The problem guarantees non-empty strings, but in real applications, handle empty string inputs gracefully.
Related Problems
Understanding Binary Arithmetic
Binary arithmetic is fundamental to computer science. Understanding how binary addition works with carries helps you grasp how computers perform calculations at the hardware level.
Learn more about binary arithmetic →Disclaimer: This problem is for educational purposes. Practice the 'Add Binary' problem on LeetCode.