add two integers without using + or -.
This is my solution.
class Solution {
public:
int getSum(int a, int b) {
int temp=a & b;
a=a^b;
while (temp>0){
b=temp<<1;
temp=a & b;
a=a^b;
}
return a;
}
};
But it doesn't work on the cases when a=-12, b=-8.
Compare it side by side with another people's working solution, he has:
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;
}
};
which is bascially the same. Why my solution doesn't work?
while (temp>0)... if you&2 negative numbers, you get another negativewhile(temp<0)towhile (temp != 0)do you think this will work?