Easy Solution using bitwise


  • 0
    K
    class Solution {
    public:
        int getSum(int a, int b) {
            int  carry = 0;
            int res = 0;
            for(int i=0;i<32;i++){
                bool val = (a&1) ^ (b&1) ^ carry ;
                res = res | (val<<i);
                if((a&1) && (b&1))  carry = 1;
                else if((a&1) && (carry&1)) carry = 1;
                else if((b&1) && (carry&1)) carry =1;
                else    carry = 0;
                a>>=1;
                b>>=1;
            }
            return res;
        }
    };
    

  • 0
    A

    In the for loop we have ++ operator, does it violate what the question asked?


  • 2
    K

    @andyatcal for ++i we can change it with i = abs(~i)

    class Solution {
    public:
    
        int getSum(int a, int b) {
            int  carry = 0;
            int res = 0;
            for(int i=0;i<32;){
                bool val = (a&1) ^ (b&1) ^ carry ;
                res = res | (val<<i);
                if((a&1) && (b&1))  carry = 1;
                else if((a&1) && (carry&1)) carry = 1;
                else if((b&1) && (carry&1)) carry =1;
                else    carry = 0;
                a>>=1;
                b>>=1;
                i = abs(~i);
            }
            return res;
        }
    };

Log in to reply
 

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