Problem Statement

Sum of Two Integers

You are given two integers, a and b, and you have to return their sum. The catch is you cannot use the + or - operators. So you have to add numbers using the way a computer stores them underneath: as bits. A bit is a single 0 or 1, and every whole number is just a row of bits (for example 2 is 10 and 3 is 11). The tool we use is bit manipulation, which means working directly on those 0s and 1s. The trick is to copy how addition works by hand: figure out the digits first, then figure out the carries, then keep going until there is nothing left to carry.

mediumBit ManipulationBit ManipulationTime: O(1) · Space: O(1)

Signals to notice

add two numbers without + or - operatorsbit manipulation onlycarry simulation

Brute force first

Not applicable in the usual sense — the constraint IS the challenge. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.

The key insight

XOR gives the sum without carries. AND shifted left gives the carries. Repeat until there are no carries. iterations max for 32-bit integers. Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.

Trace it on a=2, b=3

start: a=2 (010), b=3 (011) — b!=0, enter loop
iter1: carry=(a&b)<<1=(010&011)<<1=010<<1=100=4
iter1: a=a^b=010^011=001=1; b=carry=4 — b!=0, continue
iter2: carry=(a&b)<<1=(001&100)<<1=000<<1=0
iter2: a=a^b=001^100=101=5; b=carry=0 — b==0, exit loop
return a=5

What must stay true

a XOR b adds bits without carrying. (a AND b) << 1 produces the carries. Adding these two results is the same problem — recurse until carry is 0. As long as that statement keeps holding, you can trust the steps built on top of it.

Shape of the loop

while b != 0:
    carry = (a & b) << 1   # bits that need to carry
    a = a ^ b              # sum without carry
    b = carry             # fold carry back in
return a

Pseudocode only — the full worked solution lives in the Solution tab.

Easy way to go wrong

In languages without fixed-width integers (Python), this can loop infinitely with negative numbers. Use a 32-bit mask to simulate fixed-width arithmetic. Most mistakes here are not about syntax; they come from losing track of what your state, pointer, or structure is supposed to mean.

Bit Manipulation Pattern