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.
思路:
使用位运算,a^b得到本位和,a&b得到进位,然后将“进位”左移与“和”相异或;循环上述操作。
Code:
class Solution {
public:
int getSum(int a, int b) {
int ans=0;
while(b!=0){
ans = a^b;
b = (a&b)<<1;
a = ans;
}
return ans;
}
};