Python---非负整数转化成二进制字符串

时间:2023-01-07 08:40:13

描述:输入为一个非负整数,要求输出该整数的二进制表示,以字符串返回

关键点:位运算


class Demo:
def binary(self,n):
if n==0:
return '0'
result = []
while(n):
m = str(n%2)
result.insert(0,m)
n /= 2

return ''.join(result)

A = Demo()
print A.binary(255)
print A.binary(25)
print A.binary(10)
print A.binary(0)

Python---非负整数转化成二进制字符串