Sum of Two Integers

来源:互联网 发布:装修网络平台有哪些 编辑:程序博客网 时间:2024/06/05 10:53

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.

Credits:

Special thanks to @fujiaozhu for adding this problem and creating all test cases.


这道题同样也是看了参考才有了思路。过程就是模拟二进制加法。将要加的数字分别计算进位和不进位的两个部分,然后再将这两部分想加,直到没有进位为止就是最后的结果。

举例 3+5

3^5 得到异或的结果,也就是不进位的每一位上的结果:

011

101

------

110


然后3&5

011

101

------

001

说明在最后一位上有进位。

然后递归下去, 

110 跟 进位左移一位进行同样的计算,(001<<1 也就是 010)

---------------------------------------

110

010

------

100


110^ 010 = 100


110

010

------

010


110 & 010 = 010


-----------------------------------------

100 跟 010<<1:

100

100

-----

000


100 ^ 100 = 000


100

100

------

100


100 & 100 = 100



-------------------------------

  000

1000

-----

1000



 000

1000

------

0000


-----------------------最后一步

1000


代码:

public int getSum(int a, int b) {        //b理解成进位            if(b ==0) return a;            int add = a ^ b;            int carry = (a & b)<<1;            return getSum(add, carry);    }




0 0
原创粉丝点击