Shubham Sourabhthe room · director's cutplain résumé
Room 04 · The Grind — Bit Manipulation

Add Binary

EASY✓ CHIP-TIMEDLC #67 — FULL STATEMENT

The briefingthe full drill, in my own words

The drill: Add two binary strings the way you'd add on paper — digit by digit from the right, carrying into the next column — and hand back the binary sum as a string.

Two strings arrive, each spelled only with the characters 0 and 1 and possibly of different lengths, representing two binary numbers to be added together.

The result comes back as a single binary string holding their sum — no leading zero should pad the answer, unless the sum itself is exactly zero, in which case a single 0 is correct.

Lengths of the two inputs can differ freely, and the shorter one runs out of digits before the longer one, so any leftover carry has to keep propagating through the remaining digits alone.

  • both inputs are non-empty strings made only of '0' and '1' characters
  • the two strings may differ in length, up to roughly ten thousand characters each
  • the output must not carry a leading zero, except the single-character "0"
  • inputs never contain a sign character, whitespace, or other digits
EX 01
a = "11" · b = "1"
→ "100"
carry ripples all the way through
EX 02
a = "1010" · b = "1011"
→ "10101"
same length operands
EX 03
a = "0" · b = "0"
→ "0"
zero plus zero

The hintstake only what you need

HINT 1 THE NUDGE

Converting both strings to numbers and adding them works today, but it leans on a library doing arithmetic no different from what you'd do by hand.

HINT 2 THE STRUCTURE

Binary addition is grade-school addition in base 2: walk both strings from the last character, sum the two digits plus whatever carried in.

HINT 3 ONE STEP FROM THE ANSWER

At each column: total = digitA + digitB + carry. Write total % 2, carry forward total / 2. Keep going past the shorter string as long as a carry remains.

Coach's boardthe pattern, step by step

THE COLUMN CARRYPATTERN · CARRY SIMULATIONa = "1101" · b = "101"
1
1
0
1
1
0
1
STEP 1

Two binary strings, right-aligned: 1101 and 101. Walk from the last column, summing digit + digit + carry.

STEP 1 / 7 · ← → WORK TOO

The splitstwo paces, two languages

grind/add-binary.py — RACE PACE
LANG ▸
PACE ▸
class Solution:
    def addBinary(self, a: str, b: str) -> str:
        i, j = len(a) - 1, len(b) - 1
        carry = 0
        out = []
        while i >= 0 or j >= 0 or carry:
            total = carry
            if i >= 0:
                total += int(a[i])
                i -= 1
            if j >= 0:
                total += int(b[j])
                j -= 1
            out.append(str(total % 2))
            carry = total // 2
        return "".join(reversed(out))
TIME O(MAX(M, N))SPACE O(MAX(M, N))PYTHON · RACE PACE · 16 LN

✓ CHIP-TIMEDALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED