1-line bit manipulation and 3-line math solutions 0ms in C++, well-explained


  • 1

    Brief explanation here:

    • using bit manipulation to split the a+b process
    • 100 + 011 = 111 using ^ can help us to add different bits
    • 100 + 100 = (100 & 100) << 1 = 1000 using & can help us handle the same bits

    then we're done here getSum(a, b) -> getSum(a^b, (a&b)<<1)

    class Solution {
    public:
        int getSum(int a, int b) 
        {
            return b? getSum(a^b, (a&b)<<1):a;
        }
    };
    

    An intuitive math solution is also enclosed here.

    class Solution {
    public:
        int getSum(int a, int b) 
        {
            if(a < b) swap(a, b);
            if(a==INT_MAX && b==INT_MIN) return -1;
            return (log(pow(1.1, b)*pow(1.1,a))/log(1.1));
        }
    };

Log in to reply
 

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