πŸ“ Problem Details

input integers a and b return the sum of the two integers constraint: can’t use the operators + and -

πŸ’‘ Explanation of Solution

Bit Manupulation:
1. Use XOR (^) to get the sum without carry
2. Use AND (&) followed by a left shift ( << ) to get the carry
3. Repeat the process until the carry is 0

βŒ› Complexity Analysis

Time Complexity: O(1)
Space Complexity: O(1)

πŸ’» Implementation of Solution

class Solution {
public:
    int getSum(int a, int b) {
        while(b != 0) {
            unsigned carry = (unsigned)(a & b) << 1; // calculate carry
            a = a ^ b; // add without carry
            b = carry; // carry gets added in the next iteration
        }
        return a;
    }
};