C++ solution with explanation 3ms


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

    Every loop, we shift our result number to left by 1 digit. Then update result number. If the rightmost digit of n is 1 then update result number last digit be 1. If the rightmost digit of n is 0 then update result number last digit be 0. Then shift n to right by one for another update

    I use 8 bit int as example to explain my idea:
    For example we want to reverse 01010101.

    loop     res                 n
    0          0             01010101
    1          1             0101010
    2          10            10101
    3          101           01010
    4          1010          0101
    5          10101         010
    6          101010        10
    7          1010101       0
    8          10101010      0
    

  • 0
    C

    @beckswu great idea!


Log in to reply
 

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