本帖最后由 ButcherRabbit 于 2017-5-20 01:25 编辑 def Dec2Bin(dec):
result = ''
if dec: #dec地板除结果不为0
result = Dec2Bin(dec//2) #递归关系我倒是理解了,问题在于下一步
return result + str(dec%2) #将所得 余数 添加到字符串内 如果没有上一步 对 result的 “赋值操作”我完全理解这个函数
else:
return result
我们用这个代码分析最简单的吧 Dec2Bin(3),转换为2进制是不是11
dec = 3 result ='' if dec: 条件成立, result=Dec2Bin(1),然后返回 "Dec2Bin(1)+1"对吧
Dec2Bin(1)等于多少呢:
dec = 1 result ='' if dec: 条件成立, result=Dec2Bin(0),然后返回 "Dec2Bin(0)+1"对吧
Dec2Bin(0)等于多少呢:
dec = 0 result ='' if dec: 条件不成立, 直接返回 ""对吧
逆推回去,Dec2Bin(3) 返回的是不是"'' + 1 + 1" 就是返回'11'呢
你自己试着逆推一下喽,一直result都是空的 |