Easy to understand C++ code (9ms)

  • 2

    Basically, this code is just keeping pop the last bit from n and push it to the end of the return result.


    • Get last bit from n
    • Push the bit to the end of the result
    • Pop out the last bit of n

    Until n is 0

    • Push remaining 0s to the n by "ret << nShift"
    • Return the result "ret"
            uint32_t ret = 0;
            int nShift = 32;
            while (n && nShift--)
                // shift ret to left by one and move a room for the new push
                ret = (ret << 1);
                // Push the last bit of the n to ret
                if (n%2)
                    ret |= 0x1;
                // pop the last element out
                n = (n>>1);
            return ret << nShift;

Log in to reply

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