LeetCode #371 Medium

Sum of Two Integers

Add two integers without + or - by folding XOR (sum without carry) with (a & b) << 1 (the carry) until the carry vanishes.

bit-manipulation
Open on LeetCode ↗
02

Intuition

💡

It is easy to think XOR alone computes addition, but XOR only gives the sum WITHOUT carrying -- 1^1 lands on 0 and silently throws away the carry that a real addition would produce. The fix is to compute the carry separately: a & b marks every position where both bits were 1, and shifting that left by one places the carry where it belongs for the next column, exactly like carrying a digit in grade-school addition. A single pass is not enough, because folding the carry back in can itself produce a new carry, so you loop -- treating the running sum as the new 'a' and the carry as the new 'b' -- until the carry finally reaches zero. In Python, integers are arbitrary precision, so negative numbers do not wrap the way they do in a fixed-width language; you have to explicitly mask to 32 bits at each step and reinterpret the top bit as a sign to get correct two's-complement behavior.

03

Approach

1

Compute sum without carry via XOR

a ^ b adds each bit position independently and ignores any carry out of that position -- it is correct wherever the two bits differ, and wrong (drops a 1) wherever both bits are 1.

2

Compute the carry via (a & b) << 1

a & b identifies every bit position where both operands had a 1, meaning a carry was generated there. Shifting that result left by one moves each carry into the next higher bit position, ready to be added in.

3

Loop until the carry is zero

Set a to the XOR result and b to the carry, then repeat. Because Python ints do not wrap at 32 bits, mask both to 0xFFFFFFFF on every step, and once the loop ends, reinterpret the top bit as a sign bit to recover the correct negative value if needed.

04

Solution & live demo

python
1class Solution:
2 def getSum(self, a: int, b: int) -> int:
3 MASK = xFFFFFFFF
4 a, b = a & MASK, b & MASK
5 while b != 0:
6 carry = ((a & b) << 1) & MASK
7 a = (a ^ b) & MASK
8 b = carry
9 return a if a < x80000000 else ~(a ^ MASK)
05

Edge cases

a = 0 or b = 0

The carry (a & b) << 1 is immediately 0, so the loop exits after zero or one iteration with the nonzero operand as the answer.

Both a and b negative

After masking to 32 bits, the same XOR/carry loop works identically -- the two's-complement bit pattern handles sign automatically.

Result exceeds 32-bit signed range in a wrapping sense

All intermediate values are masked to 0xFFFFFFFF each iteration to simulate fixed-width overflow the way a real 32-bit adder would.

Final result's top bit is set

Reinterpret the masked 32-bit value as negative (two's complement) before returning, since Python would otherwise treat it as a large positive number.

06

Complexity

Time
O(1) -- at most 32 iterations
Space
O(1)
undefined