您的位置:首页 > 其它

leetcode-371. Sum of Two Integers

2016-07-17 00:44 471 查看
1、来源:点击打开链接

2、题目:

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.

3、代码(主要还是参考了这里点击打开链接):

class Solution {
public:
int getSum(int a, int b) {
int c,d;
c=a^b;
d=a&b;
return d==0?c:(getSum(c,(d<<1)));
}
};

4、原理1:
 01
00001
10111
原理2:

如果a,b相加没有进位,则a^b即为a+b;

若是有进位,则可以使用a^b,与(a&b)<<1相加即可

5、加油啦~~写一点点博客也好,也要坚持下呢,小hao同学加油~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: