C++ 0ms 2 lines recursive solution


  • 3
    class Solution {
    public:
        int getSum(int a, int b) {
            if (b == 0) return a;
            return getSum(a ^ b, (a & b) << 1);
        }
    };
    

    XOR operation is the same as bit addition without considering the carry.
    (a & b) << 1 is the carry, only a and b are both 1 will result in a carry of 1.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.