Reversing a number in Python

72 views Asked by At

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:

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.

2

There are 2 answers

3
quamrana On BEST ANSWER

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]
0
OysterShucker On

You can use divmod for this. divmod will give you the results of floor division and modulo, in one line.

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

# As long as x is greater than 0
while x:
    # Assign x with x divided by 2
    x, xm2 = divmod(x, 2)
    # Output x modulo 2
    out.append(xm2)
    
print(out)