lintcode 1:A+B问题

给出两个整数a和b, 求他们的和, 但不能使用 + 等数学运算符。

a和b都是 32位 整数。

肯定是用位操作符号来实现,那就要推算一下过程,数位和进位位。

0+0=0

0+1=1

1+0=1

1+1=0

所以a^b是没有进位的时候得到的数位。

而只有在1+1的时候会产生进位,所以a&b是进位的结果。

要得到进位的结果,就是(a&b)<<1,再把这个结果和没算进位的结果相加即可。直到进位为0,结束运算。

class Solution {
public:
    /*
     * @param : An integer
     * @param : An integer
     * @return: The sum of a and b
     */
    int aplusb(int a, int b) {
        // write your code here
        
        int cin,cur;
        do{
            cur = a^b;
            cin = (a&b)<<1;
            a = cur;
            b = cin;
        }while(b!=0);
        return a;
    }
};
原文地址:https://www.cnblogs.com/rimochiko/p/8250295.html