LeetCode——Sum of Two Integers
Question
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.
Solution
异或操作有累加的效果,但是没有进位的效果。什么时候进位呢? 同时为1的时候进位,往前进一位,所以用交集操作,再移位,表示进位。
Answer
class Solution {
public:
int getSum(int a, int b) {
int sum = a;
while(b != 0) {
sum = a ^ b;
b = (a & b) << 1;
a = sum;
}
return sum;
}
};