Converting an integer to base 2
Scott David Daniels
Scott.Daniels at Acm.Org
Sat Dec 1 18:40:22 EST 2001
On Sat, 1 Dec 2001 16:44:40 -0300, "Alves, Carlos Alberto - Coelce" <calves at coelce.com.br> wrote:
> Yeah, it works. But not for n=0, when we get the wrong result '' intead '0'.
> >>> def ito2(n):
> if n < 1:
> return ''
> else:
> return itoa2(n / 2) + str(n & 1)
>
>
> >>> ito2(0)
> ''
How about:
def ito2(n):
if n < 2:
return str(n)
else:
return ito2(n / 2) + str(n & 1)
More information about the Python-list
mailing list