Given two integers a and b, return the sum of the two integers without using the operators + or -.
Output: 3
Explanation: 1 + 2 = 3, computed using XOR and carry.
Output: 5
Explanation: 2 (010) XOR 3 (011) = 001, carry = 100; 001 XOR 100 = 101 = 5.
Binary addition works in two steps: XOR gives the sum without carry, and (a & b) << 1 gives the carry. Repeat until there is no carry.
- XOR a and b to get the sum without carry.
- AND a and b then shift left to get the carry.
- Set a = sum, b = carry and repeat until carry is 0.
- Return a when b becomes 0.
Complexity Analysis:
Time complexity: O(1) — bounded by 32 bit positions.
Space complexity: O(1) — constant extra space.