InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Bit Manipulation

Add Binary

easy Original ↗ 00:00

Problem

You are given two non-negative integers written as binary strings a and b. Return their sum, also as a binary string. Neither input has leading zeros (except the string "0" itself), and your output should follow the same rule. The two strings may have different lengths.

Examples

  • a = "11", b = "1""100" — 3 + 1 = 4, which is 100 in binary.
  • a = "1010", b = "1011""10101" — 10 + 11 = 21.
  • a = "0", b = "0""0" — nothing to carry.

Constraints

  • 1 <= a.length, b.length <= 10^4
  • Each string consists only of '0' and '1', with no leading zeros beyond a lone "0".

Lengths up to 10^4 mean the sum can be about 10^4 bits wide. Python’s arbitrary-precision integers handle that, but the interview point is to add correctly without relying on a fixed-width integer type that would overflow.

Think about it first

Hint 1 Think grade-school addition: line the strings up at the right end and add column by column, carrying a `1` whenever a column sums to 2 or 3.
Hint 2 On bits, `x ^ y` adds without carrying, and `x & y` marks the columns where a carry is generated. Shift that carry left by one to move it into the next column.
Hint 3 Keep folding: `answer = x ^ y`, `carry = (x & y) << 1`, then repeat with those two until the carry is `0`. What is left in `x` is the sum.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug