371. Sum of Two Integers using bitwise operators

  • 0
    int getSum(int a, int b) {
        /*Check any of the input is zero; if both are zero return zero*/
        if(a == 0 && b == 0)return 0;
        if(a==0)return b;
        if(b==0)return a;
        /*To prevent overflow of int, using long as local variables*/
        long carry = 0;
        long a_l = a;
        long b_l = b;
            /*calculate carry*/
            carry = a_l&b_l;
            /*use xor logic*/
            a_l = a_l^b_l;
            /*sift the carry*/
            b_l = carry <<1 ;
        return a_l;    

Log in to reply

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