题目:
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.
链接:
https://leetcode.com/problems/sum-of-two-integers/#/description
3/14/2017
做错了
抄别人的,并附带解释:
For this, problem, for example, we have a = 1, b = 3,
In bit representation, a = 0001, b = 0011,
First, we can use "and"("&") operation between a and b to find a carry.理解:carry里面有所有需要进位的bit
carry = a & b, then carry = 0001
Second, we can use "xor" ("^") operation between a and b to find the different bit, and assign it to a,
Then, we shift carry one position left and assign it to b, b = 0010.
Iterate until there is no carry (or b == 0)
把整个解释全读下来,似乎理解了一些。
首先bit运算里or是没有进位的,所以我们将carry单独作为一个数来对待。
因为没有进位,所以xor的时候就是在两个数相加并且没有carry时候的和。(0+0=0, 0+1=1,1+0=0)
所以两数相加也就变成了carry和没有carry的和的相加。
因为carry作用在高一位,所以b = carry << 1
另外因为carry是来自于低位的,所以整个过程中carry的位数逐渐左移,并最后为0(b != 0的判断条件)
所以a就慢慢在循环中吸收了carry,成为最后的和。
**当然,还需要考虑负数相加,等我慢慢来想想。
1 public class Solution { 2 public int getSum(int a, int b) { 3 if (a == 0) return b; 4 if (b == 0) return a; 5 6 while (b != 0) { 7 int carry = a & b; 8 a = a ^ b; 9 b = carry << 1; 10 } 11 return a; 12 } 13 }
介绍bit manipulation非常好的评论:
https://discuss.leetcode.com/topic/49771/java-simple-easy-understand-solution-with-explanation
以及将来面试前必须要看的网页