1

This question relates to the leetcode question to reverse bits of a 32 bits unsigned integer.

I tried the following code:

class Solution:
    # @param n, an integer
    # @return an integer
    def reverseBits(self, n):
    
        result = 0
        BITMASK = 1

        for i in range(32):

            temp = n & BITMASK

            result = result | temp

            n = n >> 1
            
            result = result << 1

        return result

The strategy I was trying is to bitwise AND the last bit of the number with 1, then bitwise OR it with the result. The number is then right shifted by 1 to drop last bit, and the result is left shifted to make room for the next bit result. The code doesn't generate the correct result. Can someone help me understand how to fix this code ? Thanks.

1
  • 1
    return int(bin(n)[2:].zfill(32)[::-1], base=2) ? Very navie approach though Commented Feb 21, 2021 at 9:01

1 Answer 1

3

Try this

class Solution:
    def reverseBits(self, n: int) -> int:
        bitmask = 1
        result = 0
        
        for i in range(31):
            temp = n & bitmask
            result = result | temp
            n = n>>1
            result = result<<1

        temp = n & bitmask
        result = result | temp
        return result

The main thing is that, when your code runs 32 times then at last it again shifts the result which gives the error, we need to run the code 31 times and last step of AND and OR keep it outside of the loop.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.