loading

Sum of Two Integers — Step-by-Step Visualization

mediumLeetCode #371MathBit Manipulation

Given two integers `a` and `b`, return the sum of the two integers without using the operators `+` and `-`.

Algorithm Pattern

Bit Manipulation (XOR + Carry)

Key Idea

XOR gives the sum of bits without carry. AND shifted left gives the carry. Repeat until carry is zero.

Step-by-Step Approach

  1. Compute carry = (a & b) << 1.
  2. Compute partial sum a = a ^ b.
  3. Set b = carry.
  4. Repeat while b != 0.
  5. Return a (no remaining carry).

Common Gotchas

  • In Python, integers are unbounded — a 32-bit mask is needed to handle negatives.
  • In JS, bitwise ops already operate on 32-bit signed integers.

Related Problems