Skip to content
mlmentorship

Sum of Two Integers

Separate sum bits from deferred carries, preserve a finite modular sum, then decode the requested signed or unsigned result.

Published · 13 min read ·Core ·Mixed

ML breadth · active recall

Practice before you read

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

ML breadth · closed-book attempt

Sum of Two Integers

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

Problem

Input. Two 32-bit signed operands, first and second, or their corresponding unsigned 32-bit word patterns. Output. Return their sum interpreted as a signed 32-bit integer, wrapping on overflow. Rules. Do not use arithmetic + or - to implement the addition. The result follows 32-bit two's-complement behavior, not Python's unbounded-integer sum. Only the low 32 bits belong to the word; the highest bit determines its signed interpretation. Example. Inputs 1 and 2 return 3; inputs -2 and 3 return 1. Inputs 2147483647 and 1 return -2147483648 because signed overflow wraps.

08:00recommended time

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

30-second answer map

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

Problem trace

Compute carry and carry-free sum from the same old operand pair

Worked example: simultaneous XOR and shifted-AND updates preserve the totalAt every row, provisional sum and carry together preserve the total. XOR resolves positions without overlapping ones; overlapping ones become carry in the next position. Repeat until no carry remains.Provisional sum and shifted carrypreserve the same total separatelyShown: low four bits; higherpositions are zeroInput: sum 5; carry 301010011Pass 1: sum 6; carry 201100010Pass 2: sum 4; carry 401000100Pass 3: sum 0; carry 800001000Pass 4: sum 8; carry 010000000Every row totals eight. Stop onlywhen the shifted carry is zero.
Read it this way: At every row, provisional sum and carry together preserve the total. XOR resolves positions without overlapping ones; overlapping ones become carry in the next position. Repeat until no carry remains. At the four-and-four snapshot, why does XOR become zero while the carry moves to eight?
Full interview answer 13 min read

Add two fixed-width integer words without using arithmetic addition or subtraction in the implementation.

Problem

Input. Two 32-bit signed operands, first and second, or their corresponding unsigned 32-bit word patterns.

Output. Return their sum interpreted as a signed 32-bit integer, wrapping on overflow.

Rules. Do not use arithmetic + or - to implement the addition. The result follows 32-bit two’s-complement behavior, not Python’s unbounded-integer sum. Only the low 32 bits belong to the word; the highest bit determines its signed interpretation.

Example. Inputs 1 and 2 return 3; inputs -2 and 3 return 1. Inputs 2147483647 and 1 return -2147483648 because signed overflow wraps.

Picture

For one position, XOR retains a single one; two ones instead produce a carry of twice that position’s weight.

First bitSecond bitXOR sum bitAND carry bit
0000
0110
1010
1101

The trace shows four low columns for 7 + 5. Its mask and computation still use 32 bits.

Problem trace

Separate full-width operands: carry and provisional sum share the same old inputs

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.
834221read10
examplefirst=7, second=5; four low bits of 32columnsweights 8 4 2 1; labels are bit positionsfirst0111 (7)second0101 (5)mask1111…1111 (32 bits)
read
3
example
first=7, second=5; four low bits of 32
columns
weights 8 4 2 1; labels are bit positions

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.
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.
Check: Why must both new operands use the old pair? Why is the four-bit picture not a complete signed-number representation?
Reference drawing

Problem trace

Compute carry and carry-free sum from the same old operand pair

Worked example: simultaneous XOR and shifted-AND updates preserve the totalAt every row, provisional sum and carry together preserve the total. XOR resolves positions without overlapping ones; overlapping ones become carry in the next position. Repeat until no carry remains.Provisional sum and shifted carrypreserve the same total separatelyShown: low four bits; higherpositions are zeroInput: sum 5; carry 301010011Pass 1: sum 6; carry 201100010Pass 2: sum 4; carry 401000100Pass 3: sum 0; carry 800001000Pass 4: sum 8; carry 010000000Every row totals eight. Stop onlywhen the shifted carry is zero.
Execution trace
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.
834221read10
examplefirst=7, second=5; four low bits of 32columnsweights 8 4 2 1; labels are bit positionsfirst0111 (7)second0101 (5)mask1111…1111 (32 bits)
read
3
example
first=7, second=5; four low bits of 32
columns
weights 8 4 2 1; labels are bit positions

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.
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.
Check: Why must both new operands use the old pair? Why is the four-bit picture not a complete signed-number representation?
Read it this way: At every row, provisional sum and carry together preserve the total. XOR resolves positions without overlapping ones; overlapping ones become carry in the next position. Repeat until no carry remains. At the four-and-four snapshot, why does XOR become zero while the carry moves to eight?

Code

Both right-hand expressions read the old operands. Tuple assignment commits their results together.

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)

Preserve the Modular Sum

At each loop boundary, first + second modulo 2**32 equals the original modular sum.

After the first commit, both stored values are masked words. Any lowest unresolved carry moves left each following pass, eventually vanishing or exiting the word.

The pictured pair progresses (7,5) -> (2,10) -> (8,4) -> (12,0).

Without finite masking, Python sign extension can propagate a carry indefinitely.

Decode the Completed Word

When carry is zero, the low word is complete. Values below 0x80000000 are already nonnegative signed results.

For larger words, ~(first ^ mask) decodes the same bits as a negative Python integer.

For example, 2147483647 + 1 wraps to -2147483648, not the unbounded mathematical sum.

The source assumes 32-bit operands. Arbitrary large inputs are not normalized when the loop is skipped.

For a fixed 32-bit width, time and space are . Word width must be included when the interface changes.

Recall: Why must the two expressions use old operands? Updating first early changes which original pairs generate carries.

Declare a Signed Width

Choose this when: The finite signed representation is an input parameter rather than 32 bits.

Normalize both operands before entering the loop. This also handles arbitrary integer inputs modulo the declared width.

def add_signed_width(first, second, width):
   if width <= 0:
      raise ValueError("positive width required")
   mask = ~(~0 << width)
   first, second = first & mask, second & mask
   while second:
      first, second = (first ^ second) & mask, ((first & second) << 1) & mask
   sign = (mask >> 1) ^ mask
   return first if not first & sign else ~(first ^ mask)

Width must be a positive integer. The mask and sign formulas avoid arithmetic addition and subtraction.

At width eight, 127 with 1 gives -128; -1 with 1 gives zero.

Carry resolution takes at most width passes. Python’s bit operations and retained integer storage depend on width.

Return an Unsigned Pattern

Choose this when: The consumer wants an integer in 0..2**32-1, not signed decoding.

Normalize both operands, call the reference, then mask the signed result back to its word pattern.

def add_unsigned32(first, second):
   mask = 0xFFFFFFFF
   return get_sum(first & mask, second & mask) & mask

0xFFFFFFFF with one wraps to zero. 2147483647 with one gives unsigned 2147483648.

The same completed bits can therefore have different signed and unsigned interpretations. Overflow still wraps modulo 2**32.

Normalizing before the call matters when second becomes zero before any loop iteration. For this fixed width, time and space are constant.

Transfer

The invariant preserves a modular quantity while moving unresolved work toward a finite boundary. Changing the output interpretation does not change the carry computation.