My 3ms pure C solution


  • 72
    uint32_t reverseBits(uint32_t n) {
        uint32_t m = 0;
        for (int i = 0; i < 32; i++, n >>= 1) {
            m <<= 1;
            m |= n & 1;
        }
        return m;
    }
    

    The process is straightforward, just iterate over all bits.


  • 2
    P

    very brilliant idea, so concise


  • 2
    Y

    @xcv58
    It's going like a circle. Good idea.


  • 1
    B

    @xcv58 It would be very helpful if you could explain your approach. From what I understand, you are working like this:

    • By m<<=1, you are left-shifting the value of m by 1 bit in every iteration.

    • By m|=n&1, i.e., m=m|n&1you are checking if the LSB of m or the LSB of n is set, in which case you are setting the LSB of m. Then you move on to the next bit and so on...

    However, in what way is this reversing the order of the set bits?

    Thank you for your help. I really appreciate it!


  • 1
    S

    @BatCoder Here we get the LSB of n and set it to m . On each iteration, we left-shift m by 1 position. The LSB's of n become MSB's of m. This reverses the order of bits. HTH!


  • 0
    B

    @skylake26 Thank you. I appreciate your help! :)


Log in to reply
 

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