23/24课 递归十进制转换 (欢迎新手一起学习)
def Dec2Bin(dec):result = ''
if dec:
result = Dec2Bin(dec//2)
return result + str(dec%2)
else:
return result
print(Dec2Bin(10))
'''result= IDec2Bin(10//2) I
I result + str(10%2) IDec2Bin(5//2) I
I ------------------ Iresult + str(5%2) IDec2Bin(2//2) I
101 + str(10%2) I ------------------ Iresult + str(2%2) IDec2Bin(1//2)
return'1010' I'10' + str(5%2) I ------------------ Iresult + str(1%2) I
return'101' I'1'+str(2%2) I -------------------IDec2Bin(0//2)
I return'10' I Ireturn result + str(dec%2)
I'0' + str(1%2) I当 dec== 0 / 直接 return ' '
Ireturn '1' I 初始化 result= ' '
result='1010'<<============ Ireturn ' ' + str(0%2)
result='101'<<============== I return '0'
result='10'<<=================
result='1'<<=================
result='0'<<===================== '''
有错 多多 指教,复制 代码 :sweat:去看 比较整齐 {:7_144:}吐槽~。
二进制以0b开头。 请教一下,当递归到Dec2Bin(0//2)的时候,我的理解是此时的dec应该是0,那么是0就不会进入if语句中,而会执行else语句,那么结果就应该是return ' ',为什么会有+str(0%2)在后面呢
页:
[1]