Home > database >  How to Reverse A String in a loop
How to Reverse A String in a loop

Time:10-18

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

CodePudding user response:

You are just printing the binary numbers one at a time in the loop, you can't relay reverse when they are printed one after another like that.

You could instead insert the binary elements in a list like this

num = 19

remainder = 0
binary = []
while num > 0: 
    remainder = num%2
    num = num//2
    binary.insert(0,str(remainder))

print("".join(binary))

CodePudding user response:

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

s = ''
remainder = 0
while num > 0:
    remainder = num%2
    num = num//2
    s  = str(remainder)

print(s[::-1])

You were reversing individual digits, i.e."1", "0" instead of the whole final string. Obviously, reversing strings with length 1 does not do anything.

Alternatives:

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

s = ''
while num:
    bit = num & 1
    s  = str(bit)
    num >>= 1

print(s[::-1])

Or simply:

print(bin(int(input("Enter a number: "))))

CodePudding user response:

you can remove the newline after a print by doing:

print(x[::-1], end='')

  • Related