這是一道很棒的題,對位運(yùn)算的理解十分有幫助锋拖,嗯诈悍,好好回憶對比計組里的加法。兽埃。侥钳。
我的解法
反正我還是沒用+和-嘛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;
}
};
人家的解法
好好學(xué)習(xí)一下,嗯柄错。
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;
}
};