#decimalToBinary
num=int(input("Enter number"))
while num!=0:
bin=num%2
num=num//2
print(bin,end=" ")
Let's say the input,here, is 13. It'll give the output:1 0 1 1.
How can I print it in reverse (i.e, 1 1 0 1) ?
#decimalToBinary
num=int(input("Enter number"))
while num!=0:
bin=num%2
num=num//2
print(bin,end=" ")
Let's say the input,here, is 13. It'll give the output:1 0 1 1.
How can I print it in reverse (i.e, 1 1 0 1) ?
Store it in a list, then print it in reverse.
#decimalToBinary
num=int(input("Enter number"))
output = []
while num!=0:
bin=num%2
num=num//2
output.append(bin)
print (output[::-1])
To print the results as a string
print (' '.join([str(o) for o in output[::-1]]))
EDIT As suggested in comments, Here is the approach avoiding lists.
#decimalToBinary
num=int(input("Enter number"))
output = ''
while num!=0:
bin=num%2
num=num//2
output = str(bin) + output
print (output)
Without resorting to some more difficult tricks trying to manipulate where you print things in a console, it might be easier to build up a string in the loop:
num=int(input("Enter number"))
digits = []
while num!=0:
bin=num%2
num=num//2
digits.append(bin)
and reverse it afterwards:
print(digits[::-1]) #this will possibly need formatting.
To format this with spaces try:
print(" ".join(str(x) for x in L[::-1]))
You can build the whole result in a string, then reverse it :
num = 13
bin = ""
while num!=0:
bin += str(num%2) + " "
num=num//2
bin = bin.strip();
print(bin[::-1])
Outputs :
1 1 0 1
for your example this should work:
num=int(input("Enter number"))
lst=list()
while num!=0:
bin=num%2
num=num//2
lst.append(bin)
print(lst,lst[::-1])
output:
Enter number13
[1, 0, 1, 1] [1, 1, 0, 1]
Well, you could append the values of bin in an array or just make bin an array and append to it and then print the array in reverse.
from __future__ import print_function
num=int(input("Enter number"))
bin = []
while num!=0:
bin.append(num%2)
num=num//2
print(*bin[::-1], sep=' ')