将十进制数转化为二进制数

注:bin(数字) 可以把数字转化为2进制

>>> bin(50)
'0b110010'

(0b不用管)

我的方法:

 def ct2(a):
int(a)
s=''
while(a//2!=0):
haha=a%2
s=s+str(haha)
a=a//2
s=s+str(a%2)
tmp=len(s)-1
ss=''
while(tmp>=0):
ss=ss+s[tmp]
tmp=tmp-1
return ss


测试:

>>> ct2(5)

'101'

>>> bin(5)

'0b101'


>>> bin(100)
'0b1100100'

>>> ct2(100)
'1100100'


>>> bin(1211)
'0b10010111011'
>>> ct2(1211)
'10010111011'


改进后的方法:

>>> def c2(a):
s=[]
while a:
j=a%2
a=a//2
s.append(j)
ss=''
while s:
ss=ss+str(s.pop())
return ss

测试:
>>> c2(50)
'110010'
>>> bin(50)
'0b110010'
>>> c2(100)
'1100100'
>>> bin(100)
'0b1100100'


我的问题

1不会很好的运用while

2.没有想要运用列表.append() 和 pop()

3我不会用bin() 这个方法....

posted on 2017-07-31 02:19  我是蒟蒻  阅读(305)  评论(0编辑  收藏  举报

导航