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

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解决。

 

posted @ 2015-08-24 17:35  响亮的菠萝  阅读(348)  评论(0)    收藏  举报