Clean short C++ solution, maybe you like it


  • 1
    class Solution {
    public:
        uint32_t reverseBits(uint32_t n) {
            auto r = 0;
            for (auto i = 0; i < 32; ++i) {
                r <<= 1;
                r |= n & 1;
                n >>= 1;
            }
            return r;
        }
    };

  • 0
    J

    why do we need r >> 1 at the last line?


  • 0

    Cause r is the next bit to fit n & 1, that's why r's type is uint64_t. Read for loop carefully, and you will figure it out.


  • 0
    2
    uint32_t reverseBits(uint32_t n) {
        uint32_t ret=0;
        for(int i=0; i<32; i++) {
            ret<<=1;            
            if(n&1) {
                ret|=1;
            }
            n>>=1;
        }
        return ret;
    }
    

    Maybe better?


  • 0

    Surely you can write it like that, but if is unnecessary cause shorter and faster ret |= n & 1 equals to that. Thanks anyway for reminding me. I will edit the code in case of someone being confused.

    uint32_t reverseBits(uint32_t n) {
        auto r = 0;
        for (auto i = 0; i < 32; ++i) {
            r <<= 1;
            r |= n & 1;
            n >>= 1;
        }
        return r;
    }

  • 0
    J

    Easier to understand, thanks for sharing.


Log in to reply
 

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