dimanche 17 octobre 2021

How to Reverse A String in a loop

I am writing a program to do convert a decimal number into binary, using repetitive division. I just can't reverse the final answer (which is variable "x").

num = int(input("Enter a number: "))

    remainder = 0
    while num > 0: 
        remainder = num%2
        num = num//2
        x = str(remainder) 
        #print(reversed(x))
    
        print(x[::-1])

output for num = 19

1
1
0
0
1

which is reversed from the actual answer, which is 10011 for decimal 19. Also, how can I bring the answer all in one line, so its not written vertically

Aucun commentaire:

Enregistrer un commentaire