class Solution {
public:
int getSum(int a, int b) {
int carry = 0, sum = 0, bitA, bitB;
for(int i = 0; i < 32; ++i) {
bitA = a & (1 << i);
bitB = b & (1 << i);
carry = carry << i;
sum = bitA^bitB^carry;
if((bitA&bitB)(bitB&carry)(bitA&carry)) carry = 1;
else carry = 0;
}
return sum;
}
};
Bit Manipulation C++ Straightforward Solution



@yuming.wei I have used "carry=carry&(abit) (carry&bbit)  (abit&bbit);" to update carry which according to me should do. Can anyone point out why this is not working?.
Thanks.

@kireeti2 Can you paste all your code? We cannot find the problem with knowing the declaration of the variables.
I assume that your carry, abit and bbit are the same as carry, bitA and bitB in my code and only the way of updating the carry is different from mine code, then the problem is that my updated carry is either 0 or 1, but your carry is 0 or (1<<i), so next loop your carry will shift more bits than expected.

@sasantv That's picky... I think the problem means we cannot use operator + or  to directly generate the result. If you insist, you can write another function to increment i separately without using ++i.

@yuming.wei interviewers are sometimes picky too. You must at least discuss this with your interviewer.