1

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

1
  • 1
    You can also directly convert a decimal to a binary number using bin(num) Commented Oct 17, 2021 at 17:32

3 Answers 3

2

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))
Sign up to request clarification or add additional context in comments.

Comments

1
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: "))))

Comments

0

you can remove the newline after a print by doing:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.