Python语言编程
请用Python语言编程实现由十进制数到二进制数的转换
使用循环语句;今天24点之前
python本身就有十进制数到二进制数的函数的
bin(x)Convert an integer number to a binary string. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer.
如
print(bin(5))
结果为
0b101
而自己写的网上有很多,其中之一
def my_bin(num):
la = []
if num < 0:
return '-' + my_bin(abs(num))
while True:
num, remainder = divmod(num, 2)
la.append(str(remainder))
if num == 0:
return ''.join(la[::-1])
热门标签: