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

Sum of Two Integers

MEDIUM✓ CHIP-TIMEDLC #371 — FULL STATEMENT

The briefingthe full drill, in my own words

The drill: Add two integers without touching the + or − operators — only bitwise moves are allowed, which means building addition back up from AND, XOR and shifts.

Two signed integers arrive, and the task is to produce their sum — but the classic + operator, and its cousin −, are both off-limits as the solving technique.

The result must equal what ordinary addition would produce, negative numbers included, reached instead through bitwise operations and shifts alone.

Both inputs can be negative, zero, or positive, and the sum itself must behave like standard signed addition, wrapping the same way that arithmetic normally would.

  • both a and b are signed integers within ordinary 32-bit range
  • either value can be negative, zero, or positive
  • the + and − operators may not appear in the solving technique itself
  • the result must match standard signed 32-bit addition, wraparound included
EX 01
a = 1 · b = 2
→ 3
simple positive sum
EX 02
a = -1 · b = 1
→ 0
negative and positive cancel
EX 03
a = 0 · b = 0
→ 0
both zero

The hintstake only what you need

HINT 1 THE NUDGE

Repeating a plain unit step a bunch of times gets you there and never writes a real addition between the two original numbers — but watch how slow that gets as the gap grows.

HINT 2 THE STRUCTURE

XOR adds two bits ignoring any carry; AND tells you exactly where a carry would be generated. The real problem is that a carry can itself trigger more carries.

HINT 3 ONE STEP FROM THE ANSWER

Loop: new sum = a XOR b, new carry = (a AND b) shifted left one place. Keep feeding sum and carry back in as the new a and b until the carry hits zero.

Coach's boardthe pattern, step by step

THE CARRY LOOPPATTERN · CARRY PROPAGATIONa = 15 · b = 27
32
16
8
4
2
1
A / B (BINARY)
a → 15 (001111)
b → 27 (011011)
STEP 1

Add 15 and 27 without + or −: XOR gives the sum ignoring carries, AND shifted left gives exactly where the next carry lands.

STEP 1 / 6 · ← → WORK TOO

The splitstwo paces, two languages

grind/sum-of-two-integers.py — RACE PACE
LANG ▸
PACE ▸
class Solution:
    def getSum(self, a: int, b: int) -> int:
        mask = 0xFFFFFFFF
        a &= mask
        b &= mask
        while b:
            carry = (a & b) << 1 & mask
            a = (a ^ b) & mask
            b = carry
        # a now holds the 32-bit two's complement pattern; re-sign it.
        if a > 0x7FFFFFFF:
            a -= 0x100000000
        return a
TIME O(32)SPACE O(1)PYTHON · RACE PACE · 13 LN

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