LeetCode 371.Sum of Two Integers

Description:
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.

思路

不使用算术运算求和那么只能考虑直接在二进制位上进行位运算,事实上利用异或运算(^)和与运算(&)就能完成加法运算要做的事情.
异或运算完成相加但是不进位,而与运算计算出哪些地方需要进位,在通过左移运算(<<)就可以完成进位操作了。

1.循环的方法

class Solution {
public:
    int getSum(int a, int b) {
        int sum = a;

        while (b != 0)
        {
            sum = a ^ b;
//calculate sum of a and b without thinking the carry 
            b = (a & b) << 1;
            //calculate the carry
            a = sum;
            //add sum(without carry) and carry
        }

        return sum;
    }
};

2.递归的方法

class Solution {
public:
    int getSum(int a, int b) {
       if(a && b) 
         return getSum(a^b, (a&b) << 1);
       else 
         return a|b;
    }
};
posted @ 2017-02-25 19:09  紫魔戒  阅读(119)  评论(0编辑  收藏  举报