领扣刷题日志(A + B问题)

问题摘要:计算两个整数的和并且避免使用(+)

思路:1.使用位运算(& ^)。

           2.回想int类型整数的表达形式:2's complement

           3.方法模拟全加器

答案:

//sum = carry_bit + sum_bit

int add(int a, int b){
    //I will store carry_bit in "b"
    while(b != 0){
        //only when the bits from two numbers are both 1 will carry_bit be generated.
        int carry = a & b; 
        //calculate the sum of a certain bit without considering carry
        a = a ^ b;
        //make b carry_bit so that we will continuously calculate "carry + sum"
        //notice that i_th carry is for i+1_th bit
        b = carry << 1; 
    }
    return a;
}

算法正确性解释:

1. 本算法一定会截至:

    每一次b = carry << 1; carry = a & b; 且b的位数固定,所以经过一定次数的循环后b一定会变为0;

2. 二进制数字之和=本位之和+本位右方的进位(例:00001010 + 00001100, 本为和0000 0110,右方进位1000,sum=00010110),所以只需递归求"本位之和+本位右方的进位"。

你可能感兴趣的:(Lintcode)