← DSA
MEDIUM

Sum of Two Integers

PracticeNeetCode ↗LeetCode ↗

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

Example

Input a = 1, b = 2
Output 3

Key Pointers

Step-by-Step Analysis

  1. Define mask = 0xFFFFFFFF to constrain intermediate values to 32 bits.
  2. While b (masked) is nonzero: compute carry = (a & b) << 1, then set a = (a ^ b) & mask and b = carry & mask.
  3. Once b is 0, a holds the sum as an unsigned 32-bit pattern.
  4. If that pattern's top bit is set (i.e. it represents a negative number in 32-bit two's complement), convert it back to a proper negative Python integer; otherwise return it as-is.

Complexity

Time: O(1) — bounded by 32 bit positions — Space: O(1)

Code

def getSum(a: int, b: int) -> int:
    mask = 0xFFFFFFFF
    while b != 0:
        carry = (a & b) << 1
        a = (a ^ b) & mask
        b = carry & mask
    return a if a <= 0x7FFFFFFF else ~(a ^ mask)

Code Explanation

How the solution above works, piece by piece.

  1. a ^ b adds the bits with no carrying (1 + 1 → 0).
  2. (a & b) << 1 is exactly the carry: positions where both bits are 1, moved one place left.
  3. Repeat with the partial sum and the carry until no carry remains.
  4. Python integers are unbounded, so mask keeps everything to 32 bits; a result above 0x7FFFFFFF is a negative number in 32-bit two's complement, converted back with ~(a ^ mask).
  5. At most 32 rounds: O(1).

Visual Walkthrough

Running it on a = 1, b = 2:

trace011a=1,b=2a ^ b = 3 (sum without carry), carry = 0 → 3
1 (001) and 2 (010) share no set bits, so there is no carry: one round gives 011 = 3.
1 bit

Video Explanation

NeetCode — Sum of Two Integers, LeetCode 371