My C++ solution in 9ms with bit operation


  • 0

    In my C++ solution with bit operation as follow, for i in [0,1,...30,31], if (n & (1 << i)), the ith character in the old binary code is '1', then the (32-i)th character in the reversed binary code is '1', the result should plus (1 << (32 - i - 1)).

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

Log in to reply
 

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