Coding · stretch-tier · asked at Amazon, Apple, Google, Meta, Microsoft, Netflix

Sum of Two Integers

mediumbit-manipulation

Problem

Compute a + b for two integers without using the + or - operators anywhere in your code. Only bitwise operations, shifts, comparisons, and assignments are allowed.

  • Both operands are small, well within a couple thousand in magnitude.
  • Assume the answer fits in a signed 32-bit integer. Your code must handle negative operands and negative results correctly.

Examples

  • a = 4, b = 9 → 13.
  • a = 6, b = 5 → 11. 6 ^ 5 = 3 is the sum without carries and (6 & 5) << 1 = 8 is the carry; 3 + 8 = 11, and recursing on (3, 8) gives 11 ^ 0 = 11.
  • a = -1, b = 1 → 0. In 32-bit two's complement, -1 is all ones; the carry propagates out of the top bit and is discarded, leaving 0.

Hints

  1. Add two bits by hand: the sum bit is x XOR y, the carry bit is x AND y. How do you combine these across all positions?
  2. a ^ b is the sum ignoring carries; (a & b) << 1 is the carry to add on. Repeat until there is no carry.
  3. In Python, ints are unbounded, so a negative carry shifts left forever. Mask every intermediate to 32 bits and convert the final pattern back to a signed value.

Last reviewed 8 September 2026