Bit Manipulation C++ Straightforward Solution


  • 0
    Y
    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;
        }
    };
    

  • 0
    H

    good job! one adivice:you are using + operation in your code line 9,replace it with | operation


  • 0
    Y

    @Horanol Thank you for your advice!


  • 0
    K

    @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.


  • 0
    Y

    @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.


  • 0
    S

    Good job, but you are using + in your for loop (++i).


  • 0
    Y

    @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.


  • 0
    S

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


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.