Leetcode_371_Sum of Two Integers

来源:互联网 发布:retrofit json实体 编辑:程序博客网 时间:2024/06/05 16:10


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.

Subscribe to see which companies asked this question


     
思路:

      (1)题意为给定两个整数,要求不用加减符号求它们的和。

      (2)这题属于简单题,但是需要跳出思维的墙,需找解题方法。这里考虑将数字转为二进制后进行计算,分两种情况:相加时没有进位时直接相加;有进位时要注意加上进位。首先,不考虑进位,对每一位进行相加,这里使用^(按位异或,对应位相同为0,不同为1),即a^b。然后,判断并计算进位,对于0加0、0加1、1加0而言,都不会产生进位,只有1加1时才会向前产生一个进位。因此,进位可以看成是两个数先做位与(&)运算,然后再向左移动一位(相当于乘以2)。最后,将前两步结果相加。循环上面步骤,直至进位为0((a & b) << 1的结果为0)。

      (3)代码实现如下所示。希望对你有所帮助。


package leetcode;public class Sum_of_Two_Integers {    public int getSum(int a, int b) {        while (b != 0) {            int c = a ^ b;            b = (a & b) << 1;            a = c;        }        return a;    }}
1 0
原创粉丝点击