Hi I wrote the following recursive decimal to binary function while studying for Andela.
def binary_converter(q):
if q>255 or not isinstance(q, int) or q<0:
return "Invalid input"
if q==0:
return '0'
elif q!=0:
q, r = divmod(q, 2)
return str(r)+binary_converter(q)
The code works for the most part, except I haven't figured out a way to get rid of any preceding zeros to the final result.
For example:
binary_converter(62) '0111110' That's 0111110 with a preceding 0.
How in the world do I get rid of it without breaking the code?
I've tried returning an empty string for the if condition but that breaks my ability to convert the decimal 0 to it's binary which is still 0.
Edit: Here's the working code, updated with D.W's answer
def binary_converter_for_realz(q):
if q>255 or not isinstance(q, int) or q<0:
return "Invalid input"
if q==0:
return ''
elif q!=0:
q, r = divmod(q, 2)
return binary_converter_for_realz(q)+str(r)
def binary_converter(q):
if q==0:
return '0'
else:
return binary_converter_for_realz(q)