|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
0. 使用递归编写一个十进制转换为二进制的函数(要求采用“取2取余”的方式,结果与调用bin()一样返回字符串形式)。
def Dec2Bin(dec):
result = ''
if dec:
result = Dec2Bin(dec//2)
return result + str(dec%2)
else:
return result
print(Dec2Bin(62))
上面是小甲鱼给的代码,实测print(Dec2Bin(0))无返回值,大佬们可否改进一下,顺带使其如同bin()一样,前缀带有0b?
- def Dec2Bin(dec):
- result = ''
-
- if dec:
- result = Dec2Bin(dec//2)
- return result + str(dec%2)
- else:
- return result
- def Bin(dec):
- if dec == 0:
- return '0b0'
- else:
- return '0b'+Dec2Bin(dec)
- print(Bin(62))
复制代码
|
|