The C++ solution without any extra memory


  • 3
    T

    The idea is to check the 32 bits one by one from left to right. We will get final result after we finish that loop with 32 times. In each loop, we will always do 3 things:

    1. The final result multiply by 2
    2. If the modular of original value(n) is 1, then final result add 1.
    3. Make the original value divided by 2.

    The code is as follow:

    class Solution {
    public:
        uint32_t reverseBits(uint32_t n) {
            uint32_t result = n%2;
            n=n/2;
            for(int i=0;i<31;i++)
            {
                result = result*2;
                if(n%2==1)
                    result = result+1;
                n=n/2;
            }
            return result;
        }
    };

  • 1
    X

    This solution is great. But why you use

    result = result*2;
    

    instead of

     result = (result << 1);
    

    in the 8th line, which is a faster way.

    Moreover, a cleaner solution could be as follows.

    class Solution
    {
    public:
    	uint32_t reverseBits(uint32_t n)
    	{
    		uint32_t res = 0;
    		for(int i = 0; i < 32; ++i)
    		{
    			res = res << 1;
    			if(1 == n%2)
    				++res;
    			n /= 2;
    		}
    		return res;
    	}
    };

  • 0
    T

    Yes. I agree your comments, it look like clean and more efficient. Thanks!


  • 0
    L

    I was kind of wondering why you use "n/=2" instead of "n>>=1" while you tell him to replace "result=result*2" with "result=(result<<1)" ... ^_^


  • 0
    X

    Yes, great. I don't release that until you point it out. Thank you!


Log in to reply
 

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