Simple java solution with full adder


  • 0
    C
    public int getSum(int a, int b) {
            int sum=0, carry=0,result=0;
            for(int i=0;i<32;i++){
                sum = (a & 1) ^ (b & 1) ^ carry; //calculate sum
                carry = (((a & 1) ^ (b & 1)) & carry) | ((a & 1) & (b & 1)); //calculate carry
                a >>=1;
                b >>=1;
                result |= sum<<i; //put sum into result
                if(a==0 && b==0 && carry==0) break; //early exit
            }
            return result;
    }
    

    about full adder wiki page:https://en.wikipedia.org/wiki/Adder_(electronics)


Log in to reply
 

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