문제

I recently stumbled upon this function which inverts binary representation of even numbers,but I'm not able to understand the logic behind the code?

int binaryReverse(int toReverse) {

     int reversed = 0;
     while(toReverse > 0) {
             reversed *= 2;
             reversed += toReverse % 2;
             toReverse /= 2;
     }

     return reversed;
}
도움이 되었습니까?

해결책

First of all, it doesn't invert the bits, it reverses them (and only those between the rightmost bit and the leftmost bit which is set to 1).

Second, here is how it works:

int binaryReverse(int toReverse)
{
    int reversed = 0;
    while (toReverse > 0)
    {
        reversed  *= 2;             // shift the output one bit to the left
        reversed  += toReverse % 2; // set the rightmost bit in the output to the value of the rightmost bit in the input
        toReverse /= 2;             // shift the input one bit to the right
    }
    return reversed;
}

Third, here is a possibly more readable version (though it has to take the input as unsigned):

int binaryReverse(unsigned int toReverse)
{
    int reversed = 0;
    while (toReverse > 0)
    {
        reversed  <<= 1;             // shift the output one bit to the left
        reversed   |= toReverse & 1; // set the rightmost bit in the output to the value of the rightmost bit in the input
        toReverse >>= 1;             // shift the input one bit to the right
    }
    return reversed;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top