C++ recursion solution using bit manipulation

  • 1
    1. We can use a ^ b to get the bits of the sum without considering the carry bits.
    2. We can get carry bits by using a & b like the operation above.
    3. So it become the sub-problem. We need to calculate the sum of (a^b) and (a & b) << 1.
    4. When the carry bits if zero, the function will return.
    class Solution {
        int getSum(int a, int b) {
            if(a == 0) return b;
            return getSum((a&b)<<1 , a^b);

Log in to reply

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