MediumNeetCode150MathBit Manipulation
Sum of Two Integers
Add two integers without + or - operator.
Examples
Input
a = 1, b = 2
Output
3
1+2=3 without + operator.
Constraints
- •
-1000 <= a, b <= 1000
Approaches
XOR for sum, AND for carry.
CodeT: O(32) = O(1) | S: O(1)
Loop until no carry.
CodeT: O(32) | S: O(1)
def getSum(a, b):
mask=0xFFFFFFFF
while b&mask:
carry=(a&b)<<1
a=a^b; b=carry
return a&mask if b>0 else aSame approach.
CodeT: O(32) | S: O(32) stack depth
Complexity Comparison
| Approach | Time | Space | Description |
|---|---|---|---|
| Bit Manipulation | O(32) = O(1) | O(1) | XOR for sum, AND for carry. |
| Iterative | O(32) | O(1) | Loop until no carry. |
| Recursive | O(32) | O(32) stack depth | Same approach. |
Bit Manipulation
T: O(32) = O(1)S: O(1)
XOR for sum, AND for carry.
Iterative
T: O(32)S: O(1)
Loop until no carry.
Recursive
T: O(32)S: O(32) stack depth
Same approach.
Common Mistakes
Not handling negative numbers
Infinite loop without mask
Off-by-one in mask