one bit full adder based solution


  • 0
    Z

    I have to say this is a interesting question, if you have ever taken digital logic class you will know how full adder is implemented, and this problem want you to review it again.

     int getSum(int a, int b) {
        unsigned int aa=a;
        unsigned int bb=b;
        int res=0;
        int w=1;
        int c=0;
        int s=0;
        while(aa!=0 || bb!=0){
            s=sum(aa&1,bb&1,c);
            c=cout(aa&1,bb&1,c);
            aa=aa>>1,bb=bb>>1;
            res=res|s*w;
            w<<=1;
        }
        res=res|c*w;
        return res;
    }
    
    int sum(int a,int b,int c){
        return a^b^c;
    }
    int cout(int a,int b,int c){
        return a&b||(c&(a^b));
    }

Log in to reply
 

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