371. Sum of Two Integers
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.
解题思路:既然不能用内置的加减法,那就只能用位运算。
xor:可理解为不考虑进位时的按位加;
and:and运算后值为1的位即需要进位的位置,再用移位的方法实现进位。
c++:
class Solution {
public:
int getSum(int a, int b) {
int value = a^b; //不考虑进位的按位加
int carry = a&b; //进位
int value_new;
while(carry)
{
carry<<=1;
value_new = value^carry;
carry &= value;
value = value_new;
}
return value;
}
};
Top Solution: 代码更简洁
class Solution{
public:
int getSum(int a, int b) {
int sum = a;
while (b != 0)
{
sum = a ^ b;//calculate sum of a and b without thinking the carry
b = (a & b) << 1;//calculate the carry
a = sum;//add sum(without carry) and carry
}
return sum;
}
};