Add Binary (LeetCode 67): Solution and Explanation
You receive two strings that each hold a binary number, and you must return their sum, also written as a binary string. The inputs can be far longer than any built-in integer type, so the addition has to be done digit by digit.
Watch it run step by step
Try your own input and write the code →Intuition
A tempting shortcut is to convert both strings to integers, add them, and convert back. In Python that even works because integers are unbounded, but in Java or C++ a string of a few hundred bits overflows long immediately, and interviewers usually want to see you do the arithmetic yourself. So the real question is how to add two numbers when all you have is their digits.
The answer is the same column addition you learned in school, just in base 2. Line the numbers up at their right ends, add the two digits in each column along with any carry from the column to the right, write down the low bit of that sum, and pass the high bit to the next column. In binary the column total is at most 1 + 1 + 1 = 3, so the digit you write is total % 2 and the carry you pass on is total // 2.
The only wrinkles are that the strings can have different lengths and that a carry can survive past the last digit of both inputs. Both disappear if the loop keeps running while either index is still valid or the carry is nonzero, and simply treats a missing digit as 0. Because you produce digits from least significant to most significant, you collect them in a list and reverse it once at the end instead of prepending to a string on every step.
Approach: Column addition with a carry
- Set
iandjto the last index ofaandb, startcarryat 0, and create an emptyresultlist. - Loop while
i >= 0,j >= 0, orcarryis nonzero, so a final carry still produces a digit. - Start each column with
total = carry, then addint(a[i])ifiis in range andint(b[j])ifjis in range, moving each index one step left after reading it. - Append
str(total % 2)toresultas the digit for this column. - Set
carry = total // 2, which is 1 when the column summed to 2 or 3 and 0 otherwise. - After the loop, reverse
resultand join it into the final string.
Step-by-step example
a = "1011", b = "11"
- Start with
i = 3,j = 1,carry = 0. Column one addsa[3] = 1andb[1] = 1, sototal = 2. Append 0 and setcarry = 1. - Column two:
total = 1 + a[2] + b[0] = 1 + 1 + 1 = 3. Append 1 and keepcarry = 1. Nowjis -1. - Column three: only
a[1] = 0remains, sototal = 1 + 0 = 1. Append 1 and setcarry = 0. - Column four:
total = 0 + a[0] = 1. Append 1 and keepcarry = 0. Nowiis -1 too, and with no carry left the loop ends. - The list is [0, 1, 1, 1]. Reversed and joined, the answer is "1110", which is 14 in decimal, matching 11 + 3.
Code: Python, Java, C++
1class Solution:
2 def addBinary(self, a: str, b: str) -> str:
3 result = []
4 carry = 0
5 i, j = len(a) - 1, len(b) - 1
6
7 while i >= 0 or j >= 0 or carry:
8 total = carry
9 if i >= 0: total += int(a[i]); i -= 1
10 if j >= 0: total += int(b[j]); j -= 1
11 result.append(str(total % 2))
12 carry = total // 2
13
14 return ''.join(reversed(result))1class Solution {
2 public String addBinary(String a, String b) {
3 StringBuilder result = new StringBuilder();
4 int carry = 0;
5 int i = a.length() - 1, j = b.length() - 1;
6
7 while (i >= 0 || j >= 0 || carry > 0) {
8 int total = carry;
9 if (i >= 0) total += a.charAt(i--) - '0';
10 if (j >= 0) total += b.charAt(j--) - '0';
11 result.append(total % 2);
12 carry = total / 2;
13 }
14
15 return result.reverse().toString();
16 }
17}1class Solution {
2public:
3 string addBinary(string a, string b) {
4 string result;
5 int carry = 0;
6 int i = a.size() - 1, j = b.size() - 1;
7
8 while (i >= 0 || j >= 0 || carry) {
9 int total = carry;
10 if (i >= 0) total += a[i--] - '0';
11 if (j >= 0) total += b[j--] - '0';
12 result = char('0' + total % 2) + result;
13 carry = total / 2;
14 }
15
16 return result;
17 }
18};Time and space complexity
O(max(m, n))
Each loop iteration consumes at most one digit from each string, and there is at most one extra iteration for a final carry. The final reverse and join are linear in the output length, which is at most max(m, n) + 1.
O(max(m, n))
The result list holds one character per output digit. Apart from the output itself, only a few integer variables are used.
Other approaches
Convert to integers (time O(m + n), space O(m + n))
In Python, bin(int(a, 2) + int(b, 2))[2:] gives the right answer because Python integers have arbitrary precision. In Java or C++ this fails for long inputs unless you reach for a big-integer class, and it hides the arithmetic the question is testing.
Bitwise XOR and AND loop (time O(m + n) per round, space O(m + n))
Treat the numbers as big integers and repeat sum = x ^ y, carry = (x & y) << 1 until the carry is zero. It shows off bit manipulation, but it still needs arbitrary-precision integers, and each round costs time proportional to the bit length.
Common mistakes
- Stopping the loop when both indices run out. If the last column produced a carry, you lose the leading 1, so "1" + "1" would return "0" instead of "10".
- Prepending to a string inside the loop. Each prepend copies the whole string, turning a linear algorithm into a quadratic one for long inputs.
- Adding characters directly. In languages like Java,
a.charAt(i) + b.charAt(j)adds character codes (48 for '0'), so you must subtract '0' first. - Aligning the strings from the left. Binary addition starts from the least significant bit, which is the last character, not the first.
Frequently asked questions
Why not just convert the binary strings to integers?
The inputs can be thousands of digits long, which overflows fixed-width integers in Java and C++. Even where it works, the conversion skips the digit-by-digit reasoning the problem is meant to exercise.
What is the maximum value of total in each column?
Three, when both digits are 1 and there is an incoming carry. That gives a written digit of 1 and a carry of 1, which is why total % 2 and total // 2 cover every case.
Can the result be longer than both inputs?
Yes, by exactly one digit at most. That happens when the final column produces a carry, which the loop handles by continuing while carry is nonzero.