这是一道很棒的题,对位运算的理解十分有帮助,嗯,好好回忆对比计组里的加法。。。
我的解法
反正我还是没用+和-嘛QvQ
class Solution {
public:
int getSum(int a, int b) {
if (b >= 0){
for (int i = 0; i < b; i ++)
++ a;
}else{
for (int i = 0; i > b; i --)
-- a;
}
return a;
}
};
人家的解法
好好学习一下,嗯。
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;
}
};
网友评论