w3resource

Python: Reverse the binary representation of an integer and convert it into an integer

Python Basic - 1: Exercise-138 with Solution

Write a Python program to reverse the binary representation of a given number and convert the reversed binary number into an integer.

Sample Solution-1:

Python Code:

def test(n):
    return int(bin(n)[::-1][:-2], 2)

n = 13
print("Original number: ", n);
print("Reverse the binary representation of the said integer and convert it into an integer:\n",test(n));
n = 145
print("Original number: ", n);
print("Reverse the binary representation of the said integer and convert it into an integer:\n",test(n));
n = 1342
print("Original number: ", n);
print("Reverse the binary representation of the said integer and convert it into an integer:\n",test(n));

Sample Output:

Original number:  13
Reverse the binary representation of the said integer and convert it into an integer:
 11
Original number:  145
Reverse the binary representation of the said integer and convert it into an integer:
 137
Original number:  1342
Reverse the binary representation of the said integer and convert it into an integer:
 997

Flowchart:

Flowchart: Python - Reverse the binary representation of an integer and convert it into an integer.

Sample Solution-2:

Python Code:

def test(n):
    return int(bin(n)[::-1][:-2], 2)
n = 13
print("Original number: ", n);
print("Reverse the binary representation of the said integer and convert it into an integer:\n",test(n));
n = 145
print("Original number: ", n);
print("Reverse the binary representation of the said integer and convert it into an integer:\n",test(n));
n = 1342
print("Original number: ", n);
print("Reverse the binary representation of the said integer and convert it into an integer:\n",test(n));

Sample Output:

Original number:  13
Reverse the binary representation of the said integer and convert it into an integer:
 11
Original number:  145
Reverse the binary representation of the said integer and convert it into an integer:
 137
Original number:  1342
Reverse the binary representation of the said integer and convert it into an integer:
 997

Flowchart:

Flowchart: Python - Reverse the binary representation of an integer and convert it into an integer.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to find the longest common ending between two given strings.
Next: Write a Python program to find the closest palindrome number of a given integer. If there are two palindrome numbers in absolute distance return the smaller number.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.