w3resource logo


Python Exercises

Python Challenges: Reverse the bits of an integer(32 bits unsigned)

Python Challenges - 1: Exercise-19 with Solution

Write a Python program to reverse the bits of an integer (32 bits unsigned).

Input : 1234
Output : 1260388352

For example, 1234 represented in binary as 10011010010 and returns 1260388352 which represents in binary as 1001011001000000000000000000000.

Explanation :

Python: Reverse the bits of an integer(32 bits unsigned)

Sample Solution :-

Python Code :

def reverse_Bits(n):
        result = 0
        for i in range(32):
            result <<= 1
            result |= n & 1
            n >>= 1
        return result
            
print(reverse_Bits(1234))

Output :

1260388352

Flowchart:

Python Flowchart: Reverse the digits of an integer(32 bits unsigned)

Python Code Editor:

def reverse_Bits(n):
        result = 0
        for i in range(32):
            result <<= 1
            result |= n & 1
            n >>= 1
        return result
            
print(reverse_Bits(1234))

Improve this sample solution and post your code through Disqus



Join our Question Answer community to learn and share your programming knowledge.

Solve these problems:

Java: How to convert a string to an integer in Java?

C#: Loops in c#

SQL: JOIN using more than 5 tables