- A+
所属分类:Python习题
习题要求:
使用递归的方式,对十进制的数字转为二进制。参考内容:https://www.lijinlong.cc/python/pyxt/1615.html
习题代码:
- 代码一
- def zhuan(n):
- result = ''
- if n != 0:
- result = zhuan(n//2) #zhuan(55)
- # zhuan(27)
- # zhuan(13)
- # zhuan(6)
- # zhuan(3)
- # zhuan(1)
- print(n,result)
- #1
- #3 1
- #6 11
- #13 110
- #27 1101
- #55 11011
- #110 110111
- return result + str(n%2)
- else:
- return result
- print(zhuan(110))
- 代码二
- def zhuan(n, result=''):
- if n != 0:
- result += str(n % 2)
- return zhuan(n // 2, result)
- else:
- return ''.join(reversed(result))
- print(zhuan(110),'======')
以上代码来源于:http://bbs.fishc.com/thread-87205-1-1.html ,感谢ooxx7788的帮助,加入小甲鱼QQ群来一起互动吧(528770819)