python小习题,递归实现十进制转二进制

  • A+
所属分类:Python习题

习题要求:

使用递归的方式,对十进制的数字转为二进制。参考内容:https://www.lijinlong.cc/python/pyxt/1615.html

 

习题代码:

  • 代码一
  1. def zhuan(n):
  2.     result = ''
  3.     if n != 0:
  4.         result = zhuan(n//2)  #zhuan(55)
  5.                                 # zhuan(27)
  6.                                 # zhuan(13)
  7.                                 # zhuan(6)
  8.                                 # zhuan(3)
  9.                                 # zhuan(1)
  10.         print(n,result)
  11.         #1 
  12.         #3 1
  13.         #6 11
  14.         #13 110
  15.         #27 1101
  16.         #55 11011
  17.         #110 110111
  18.         return result + str(n%2)
  19.     else:
  20.         return result
  21. print(zhuan(110))
  • 代码二
  1. def zhuan(n, result=''):
  2.     if n != 0:
  3.         result += str(n % 2)
  4.         return zhuan(n // 2, result)
  5.     else:
  6.         return ''.join(reversed(result))
  7. print(zhuan(110),'======')

以上代码来源于:http://bbs.fishc.com/thread-87205-1-1.html ,感谢ooxx7788的帮助,加入小甲鱼QQ群来一起互动吧(528770819)

李金龙

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: