异或实现加法

Calculate the sum of two integers a and b, but you are not allowedto use the operator + and -.

Example 1:

Input: a = 1, b = 2
Output: 3

Example 2:

Input: a = -2, b = 3
Output: 1
class Solution {
public:
    /* 2  0010  异或结果  0001
     * 3  0011  进位     0100  再次相加 0101
     * 即: 通过异或运算得到不带进位的和
     *     进位的求法: 按位取与后左移
     * */
    int getSum(int a, int b) {
        if(b == 0)  return a;
        else return getSum(a^b, (a&b&0xffffffff)<<1);
    }
};

猜你喜欢

转载自blog.csdn.net/futangxiang4793/article/details/88776863