0
点赞
收藏
分享

微信扫一扫

LEETCODE 面试题 05.02. 二进制数转字符串

每次将实数乘2,取出最高位的部分存到res里,实数乘2的结果再减去最高位进入下一次循环

0.625-》1.25 取出1加入res,1.25-》0.25》0.5,取出0加入res 0.5-》1 

取出1加入res,最终输入res的值0.101

class Solution(object):
def printBin(self, num):
"""
:type num: float
:rtype: str
"""
res="0."
while len(res)<=32 and num!=0:
num*=2
digit=int(num)
#print(num)
res+=str(digit)
num-=digit

return res if len(res)<=32 else "ERROR"

举报

相关推荐

0 条评论