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 a

Same approach.

CodeT: O(32) | S: O(32) stack depth

Complexity Comparison

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

Try It Yourself

Copy the optimal solution and run it in our compiler.

Open in Compiler