LintCode-A + B 用位操作模拟加法

原文链接: http://www.cnblogs.com/resonantPineapple/p/4755398.html
class Solution {
public:
    /*
     * @param a: The first integer
     * @param b: The second integer
     * @return: The sum of a and b
     */
    int aplusb(int a, int b) {
        // write your code here, try to do it without arithmetic operators.
        if(a==0)return b;  
        if(b==0)return a;  
        int x1 = a^b;  
        int x2 = (a&b)<<1;  
        return aplusb(x1,x2);
    }
};

俩位相加有四种情况:

1. 1 + 1 = 10;

2. 1 + 0 = 01;

3. 0 + 1 = 01;

4. 0 + 0 = 00;

第一种情况,即有进位,用 (a&b)<<1解决;

第二第三种情况,用a^b解决。

 

转载于:https://www.cnblogs.com/resonantPineapple/p/4755398.html

你可能感兴趣的:(LintCode-A + B 用位操作模拟加法)