All Blind 75 questions

Sum of Two Integers

FreeBit manipulationMedium75 of 75

The problem

Compute the sum of two signed 32-bit integers without using addition or subtraction operators. Use 32-bit two’s-complement wraparound if overflow occurs.

Example

a = 5, b = 3 → 8

Need a hint?

XOR adds without carry; AND identifies the carry positions.

Write pseudocode, trace the example, or note an edge case. This scratchpad does not run code.

Notes stay in this browser when storage is available.

Read the solution approach

Repeatedly compute the carry as (a & b) shifted left and the carry-free sum as a XOR b, assigning both from the old operands. Mask each intermediate to 32 bits. Stop when carry is zero, then interpret the result as signed. The mask prevents negative integers from creating an infinite carry in unbounded-integer languages.

Complexity

At most 32 carry iterations and O(1) space for fixed-width integers.

Before moving on, explain why the algorithm is correct and trace a boundary case without looking at the approach.