CodingNodes / Bit Manipulation / Sum of Two Integers System design Space play · ←→ step · R restart

Problem

Given two integers a and b, return their sum without using the + or - operators. Only bit operations are allowed.

Either number can be negative. Treat both as 32-bit values: Java and C++ do that on their own, and Python needs a 32-bit mask to imitate it.

Constraints

  • -1000 ≤ a, b ≤ 1000
  • The result fits in a signed 32-bit integer

Examples: pick one to animate

Solutions

TimeO(1) SpaceO(1)

Time: The carry moves at least one place up each round and there are only 32 places, so at most 32 rounds.

Space: A few integers: mask, x, y and carry.

Adding two bits gives a sum bit (XOR) and a carry bit (AND, moved one place left). So x XOR y is the sum with carries ignored, and (x AND y) shifted left is the carries. Add those two numbers the same way, and repeat until no carry is left. A 32-bit mask keeps the values in range, and a final check turns a pattern above 2^31 - 1 back into a negative number.