Sum of Two Integers

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

Example: Given a = 1 and b = 2, return 3.

异或的结果未能考虑到进位,而进位的信息可以通过(a&b)<<1,举个例子来说明一下

a:    001010101
b:    000101111

只考虑进位的信息,即
a&b   000000101
左移一位就是进位的信息
      00001010
class Solution {
public:
    int getSum(int a, int b) {
        if(b == 0) return a;

        return getSum(a^b, (a&b) << 1);
    }
};
class Solution {
public:
    int getSum(int a, int b) {
        int sum = 0;
        //迭代直到进位信息为0
        while(b != 0){
            sum = a^b;
            b = (a&b) << 1;
            a = sum;
        }
        return sum;
    }
};

results matching ""

    No results matching ""