Sum of Two Integers
Difficulty: Medium · Pattern: Bit Manipulation · LeetCode #371
Return a + b without using the operators + or -. The inputs are 32-bit signed integers in [-1000, 1000].
Examples
text
a = 1, b = 2 → 3
a = 2, b = 3 → 5
a = -2, b = 3 → 1Hints
- XOR adds bits without the carry. AND finds the positions that generate a carry, and shifting left moves each carry where it belongs.
- Repeat until no carry is left.
- Python integers are unbounded, so negative numbers never "overflow away". Emulate 32 bits with a mask.
Approach
text
while b != 0:
carry = (a & b) << 1
a = a ^ b
b = carryThat's the logic of a ripple-carry adder, one full-width step at a time. It takes at most 32 iterations.
Python: mask with 0xFFFFFFFF at each step so negative values wrap like two's complement, and at the end convert back: if a > 0x7FFFFFFF, return ~(a ^ 0xFFFFFFFF). JavaScript bitwise ops already work on 32-bit signed integers, so the plain loop works.
Complexity
Time: O(32). Space: O(1).
Python solution
def getSum(a, b):
MASK, MAX = 0xFFFFFFFF, 0x7FFFFFFF
a, b = a & MASK, b & MASK
while b:
a, b = (a ^ b) & MASK, ((a & b) << 1) & MASK
return a if a <= MAX else ~(a ^ MASK)JavaScript solution
function getSum(a, b) {
while (b !== 0) {
const carry = (a & b) << 1;
a ^= b;
b = carry;
}
return a;
}