Skip to content
Problem 67 · LeetCode 67(opens in a new tab)

Add Binary

EasyBit manipulation

You get two strings, a and b, that each write a non-negative whole number in base 2, using only the characters 0 and 1.

Add the two numbers and return their sum, also written in base 2 as a string. Neither input has extra zeros in front, except the string "0" itself, and your answer should not have them either.

Example 1

Input:  a = "101", b = "11"
Output: "1000"
Why:    5 + 3 = 8
2 more examples and the constraints

Example 2

Input:  a = "0", b = "0"
Output: "0"
Why:    zero plus zero is still one digit

Example 3

Input:  a = "1101", b = "111"
Output: "10100"
Why:    13 + 7 = 20

Constraints

  • 1 ≤ length of a, length of b ≤ 10,000
  • Each string contains only 0 and 1
  • No leading zeros, except for "0" itself

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Pad, then prepend each bitO(n²)
  2. Two pointers and a carryO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 10,000 bitsVerdict
Pad, then prepend each bitO(n²)
Correct; copies too much
Two pointers and a carryO(n)
Best; one pass

n = length of the longer string.

Edge cases to test

  • Both are zero. "0" + "0" must give "0", not an empty string.
  • A carry at the very end. "1111" + "1" gives "10000": the answer is one digit longer.
  • Different lengths. "100" + "110010": the shorter string runs out first and stops adding.
  • Far too long for an integer. 10,000 bits overflow every built-in integer type, so parse nothing.

Common mistakes

  • Stopping the loop when both strings run out and losing the last carry.
  • Adding the characters themselves instead of their digit values ('1' - '0').
  • Forgetting to reverse the bits, since they were collected lowest first.

How to talk through it

  1. 1Clarify. How long can the strings be? Can either be "0"? Should the answer avoid leading zeros?
  2. 2Rule out parsing. Up to 10,000 bits will not fit in any integer type, so add digit by digit.
  3. 3Describe paper addition. From the right: bit is total % 2, carry is total // 2.
  4. 4Code it with two pointers. Loop while either pointer is valid or a carry remains; append, then reverse once.
  5. 5Test out loud. Run "0" + "0", a carry that makes the answer longer, and two strings of different lengths.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?