Skip to content
mlmentorship

Sum of Two Integers

Add two integers without `+` or `-`.

Published · 5 min read ·Core ·Mixed

30-second answer map

Visual first · depth when needed

XOR writes sum-without-carry bits while shifted AND carries shared 1 bits into the next pass.

Preparing the visual…

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

How practice works

ML breadth · closed-book attempt

Sum of Two Integers

Explain the mechanism, why it works, when it fails, and one alternative.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

Add two integers without + or -.

Start with the concrete trace below. It shows the state the algorithm must carry as it runs.

Problem trace

Sum of Two Integers: XOR writes sum-without-carry bits while shifted AND carries shared 1 bits into the next pass.

Input and goalAdd two integers without `+` or `-`.
Initialize the two operandsThe loop starts with first=0111 and second=0101. Because second is nonzero, another carry-resolution pass is required.
804122inspect operands13
examplefirst = 7 (0111), second = 5 (0101), shown in 4 bitscolumns8 4 2 1first0111 (7)second0101 (5)mask1111…1111 (32 bits)

Recognize it
The prompt forbids arithmetic addition and subtraction but permits bitwise operators on fixed-width signed integers.
Keep true
At every loop boundary, first plus second modulo 2^32 equals the original sum; each pass moves unresolved carries left until second becomes zero.
Reuse it
Separate a binary operation into local output and deferred carry state; the same decomposition underlies half/full adders, bit-mask arithmetic, and fixed-width overflow reasoning.
Read it this way: The loop starts with first=0111 and second=0101. Because second is nonzero, another carry-resolution pass is required. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.

Pattern: XOR gives sum bits and AND gives carry bits.

Simple idea: XOR adds without carrying. AND finds positions that need a carry. Shift the carry left and repeat until no carry remains. The mask keeps Python within 32 bits.

def get_sum(first: int, second: int) -> int:
   mask = 0xFFFFFFFF
   while second:
      first, second = (first ^ second) & mask, ((first & second) << 1) & mask
   return first if first < 0x80000000 else ~(first ^ mask)

Cost: time and space for 32-bit integers.