leetcode-371. Sum of Two Integers

来源:互联网 发布:linux 守护进程启动 编辑:程序博客网 时间:2024/06/05 00:46

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:
 010000110111

原理2:

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

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


5、加油啦~~写一点点博客也好,也要坚持下呢,小hao同学加油~


0 0
原创粉丝点击