LeetCode 371.Sum of Two Integers

来源:互联网 发布:无尽的传说2 mac 破解 编辑:程序博客网 时间:2024/06/03 03:59

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;    }};
0 0
原创粉丝点击