I'm trying to create an algorithm that converts decimals to binary. I can't use the built-in function in python to do so. This is what I've got.
n=int(input("enter a number"))
while n > 1:
print(n%2)
n //= 2
if n % 2 ==0:
print(n%2)
else:
print(n%2)
I'm completely fine with the 1's and 0's being printed in a separate line, as long as they're correct.
It should be:
n=int(input("enter a number\n"))
while n >= 1: # Should be >= 1, not > 1.
print(n%2)
n //= 2
# Removed if else.
Also, note that this will print binary in the reverse order.
For the input 6
, the output will be:
0
1
1
Not:
1
1
0
If you want the later one, then you can store it in a list first and then print the list in the reverse order.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments