371. Sum of Two Integers【位运算】
2017/3/16 20:03:07
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.
思路:
1、^可以得到哪些bit求和后应该是1。(进位的bit应该变成0,1^1=0)
2、&可以得到哪些bit应该进位
3、由于进位后的bit是1可能和第一步得到的1再次产生进位,所以不断循环,直到不产生进位。
版本1
public class Solution { public int getSum(int a, int b) { while( b != 0 ){ int y = a ^ b; int and = (a & b) << 1; a = y; b = and; } return a; } }