Add Binary
Easy
Topics
Given two binary strings s and t, return their sum as a binary string.
The inputs carry no leading zeros apart from "0" itself, and the answer must not either.
LeetCode names the arguments a and b; the harness here calls them s and t. They are the two addends and order does not matter.
Example 1
11 over 1, the two are aligned on their right-hand ends, because a column of this addition is a single place value and the inputs can be different lengths. A column adds to 0, 1, 2 or 3, and the half that exceeds one digit carries into the column to its left. The sum is 3 digits wide against 2 for the longer input, so a carry survived past the leftmost column and had to be written as a new digit.Input: s = "11", t = "1" Output: "100" Explanation: 3 + 1 = 4.
Example 2
Input: s = "1010", t = "1011" Output: "10101" Explanation: 10 + 11 = 21.
Example 3
Input: s = "0", t = "0" Output: "0" Explanation: The one case where a leading zero is the whole answer.
Constraints
- 1 <= s.length, t.length <= 10^4
- s and t consist only of the characters 0 and 1
- Each string has no leading zero except when it is exactly "0"
Editorial — intuition, approach, complexity and pitfalls
Intuition
The reason this is not a one-liner is the input size. Ten thousand binary digits is a number with about three thousand decimal digits, so converting to an integer, adding, and converting back is only available in languages with arbitrary-precision integers. In Java or C++ it overflows long before the limit.
So do what you were taught at school: add from the right, one column at a time, carrying into the next. The only difference from decimal is that a column sum of 2 produces digit 0 carry 1, and a sum of 3 produces digit 1 carry 1.
The tidy way to handle unequal lengths is to treat a position past the end of a string as a 0 digit, rather than padding one input to match the other. That removes a whole branch.
The carry has to be checked once more after the loop. Adding "1" to "1" is the smallest case where the answer is longer than either input, and dropping that final carry is the usual bug.
Approach
- Set two cursors at the last character of each string and a carry of 0.
- While either cursor is still in range, or the carry is non-zero, take the digit under each cursor, treating out-of-range as 0.
- Sum the two digits and the carry. Append
sum % 2to the output and set the carry tosum / 2. - Move both cursors left and repeat.
- The digits were produced least significant first, so reverse the collected output before returning it.
Walkthrough
s = "1010", t = "1011"
1 0 1 0
+ 1 0 1 1
column by column, right to left
col 0: 0 + 1 + carry 0 = 1 -> digit 1, carry 0
col 1: 1 + 1 + carry 0 = 2 -> digit 0, carry 1
col 2: 0 + 0 + carry 1 = 1 -> digit 1, carry 0
col 3: 1 + 1 + carry 0 = 2 -> digit 0, carry 1
done, carry 1 remains -> digit 1
collected least significant first: 1 0 1 0 1
reversed: 1 0 1 0 1
answer "10101"
the case that catches a dropped carry
s = "1", t = "1"
col 0: 1 + 1 = 2 -> digit 0, carry 1
loop ends; the carry still has to be written
answer "10", not "0"Complexity
- Time — O(max(m, n)): one column per digit of the longer input, plus at most one more for the carry.
- Space — O(max(m, n)): the output, which is at most one digit longer than the longer input.
Common Pitfalls
- Converting to
intand back. It passes in Python and overflows in Java and C++ at the stated limit. - Dropping the final carry, so
"1" + "1"returns"0". - Forgetting to reverse. The digits come out least significant first.
- Padding the shorter string with zeros and then mishandling the index. Treating out-of-range as
0is simpler and has no off-by-one. - Building the result by prepending to a string in a loop. That is quadratic at ten thousand digits; collect and reverse instead.
Full Solution — all languages
class Solution:
def addBinary(self, s, t):
i, j = len(s) - 1, len(t) - 1
carry = 0
out = []
# The carry in the condition is what writes the extra leading digit.
while i >= 0 or j >= 0 or carry:
total = carry
if i >= 0:
total += int(s[i])
i -= 1
if j >= 0:
total += int(t[j])
j -= 1
out.append(str(total % 2))
carry = total // 2
return "".join(reversed(out))import java.util.*;
class Solution {
public String addBinary(String s, String t) {
int i = s.length() - 1, j = t.length() - 1, carry = 0;
StringBuilder out = new StringBuilder();
while (i >= 0 || j >= 0 || carry != 0) {
int total = carry;
if (i >= 0) total += s.charAt(i--) - '0';
if (j >= 0) total += t.charAt(j--) - '0';
out.append((char) ('0' + total % 2));
carry = total > 1 ? 1 : 0;
}
return out.reverse().toString();
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: string addBinary(string s, string t) {
int i = (int)s.size() - 1, j = (int)t.size() - 1, carry = 0;
string out;
while (i >= 0 || j >= 0 || carry) {
int total = carry;
if (i >= 0) total += s[i--] - '0';
if (j >= 0) total += t[j--] - '0';
out += char('0' + total % 2);
carry = total > 1 ? 1 : 0;
}
reverse(out.begin(), out.end());
return out;
}
};/**
* @param {string} s
* @param {string} t
* @return {string}
*/ var addBinary = function(s, t) {
let i = s.length - 1, j = t.length - 1, carry = 0;
const out = [];
while (i >= 0 || j >= 0 || carry) {
let total = carry;
if (i >= 0) total += s.charCodeAt(i--) - 48;
if (j >= 0) total += t.charCodeAt(j--) - 48;
out.push(String(total % 2));
carry = total > 1 ? 1 : 0;
}
return out.reverse().join("");
};