Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reversing a number in Python

I’m currently working on a introductory class to Python and this is one of the labs I’m working on.

Here is the lab prompt:

Write a program that takes in a positive integer as input, and outputs a string of 1’s and 0’s representing the
integer in reverse binary. For integer x, the algorithm is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

As long as x is greater than 0
Output x modulo 2 (remainder is either 0 or 1)
Assign x with x divided by 2

Note: The algorithm above outputs 0’s and 1’s in reverse order.

Ex: if input is 6 the output is 011

How would you solve this?

number = int(input('Enter your number\n'))
number_list = []

while number != 0:
    number = number // 2
    number_list.append((number % 2))
    number_list.reverse()
    print(number_list)

I tried converting the number into a string but was not successful. This is my best attempt at it.

>Solution :

By storing the remainder in the list, you are already reversing the list. No need to reverse it again. And again . . .

You just need to store the remainder, then divide by two.

Then print the answer outside the loop:

number = int(input('Enter your number:'))
number_list = []

while number != 0:
    number_list.append(number % 2)
    number = number // 2

print(number_list)

Example output:

Enter your number:12
[0, 0, 1, 1]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading