think like ALU


  • 0
    L
    int getSum(int a, int b) {
            int ret = 0;
            int carry = 0;
            for (int i = 0; i < sizeof(int) * 8; i ++) {// i stands for bit 0 ~ 31
                int mask = 1 << i; // focus on current bit
                int __a = a & mask; //  current bit of a
                int __b = b & mask; //  current bit of b
                int result_bit = __a ^ __b ^ carry; // current bit of a + b
                carry = ((__a | __b) & (__a | carry) & (__b | carry)) << 1; // carray bit
                ret = ret | result_bit; // collect result
            }
            return ret;
        }
    

Log in to reply
 

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