﻿ Python: Reverse the binary representation of an integer and convert it into an integer - 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: 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: Python Code Editor:

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

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿