Share my C++ solution,easy to understand


  • 0
    V

    8ms:

    class Solution {
    public:
        uint32_t reverseBits(uint32_t n) {
            int i = 0;
            uint32_t ret = 0, temp = 0;
            
            for (i = 0; i < 32; ++i)
            {
                temp = n & 1;
                ret = (ret << 1) + temp;
                n = n >> 1;
            }
            
            return ret;
        }
    };
    

    4ms:

    class Solution {
    public:
        uint32_t reverseBits(uint32_t n) {
            int i = 0;
            uint32_t ret = 0;
            
            for (i = 0; i < 32; ++i)
            {
                if ((n & 1) > 0)
                    ret = ret | (1 << (31 - i));
                n = n >> 1;
            }
            
            return ret;
        }
    };

Log in to reply
 

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