Given two integers a and b, return their sum without using the + or - operators.
Example
Input a = 1, b = 2
Output 3
Key Pointers
XOR adds two bits together and ignores the carry — it gives the sum without carrying.
AND finds where both bits are 1, i.e. where a carry is generated; shifting that left by 1 moves the carry to its correct position.
Repeat "sum without carry, then add the carry in" until there's no carry left — this is literally how addition works at the bit level.
Python integers have unbounded width, so the bit-width must be masked to 32 bits to mimic fixed-width overflow behavior, then converted back to a signed value at the end.
Step-by-Step Analysis
Define mask = 0xFFFFFFFF to constrain intermediate values to 32 bits.
While b (masked) is nonzero: compute carry = (a & b) << 1, then set a = (a ^ b) & mask and b = carry & mask.
Once b is 0, a holds the sum as an unsigned 32-bit pattern.
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.
a ^ b adds the bits with no carrying (1 + 1 → 0).
(a & b) << 1 is exactly the carry: positions where both bits are 1, moved one place left.
Repeat with the partial sum and the carry until no carry remains.
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).
At most 32 rounds: O(1).
Visual Walkthrough
Running it on a = 1, b = 2:
1 (001) and 2 (010) share no set bits, so there is no carry: one round gives 011 = 3.