0ms Bit by bit calculation and shift. Easy to understand C++ solution.


  • 0
    N
    int getSum(int a, int b) {
            int res = 0, c = 0;// c is carry
            int t1 = 0, t2 = 0, count = 0, cur = 0;
            for(int i=0;i<32;i++) {
                count = 0;
                t1 = (a >> i) & 1;
                t2 = (b >> i) & 1;
                if(t1)
                    count++;
                if(t2)
                    count++;
                if(c)
                    count++;
                    
                cur = t1 ^ t2 ^ c;
                
                if(count >= 2)
                    c = 1;
                else
                    c = 0;
                
                res = res | (cur << i);
            }
            return res;
        }

Log in to reply
 

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