Given a (decimal - e.g. 3.72) number that is passed in as a string, return the binary representation that is passed in as a string. If the fractional part of the number can not be represented accurately in binary with at most 32 characters, return ERROR.
Example
For n = "3.72", return "ERROR".
For n = "3.5", return "11.1".
class Solution:
"""
@param n: Given a decimal number that is passed in as a string
@return: A string
"""
def binaryRepresentation(self, n):
# write your code here
integer,decimal = n.split(‘.‘)
integer = int(integer)
decimal = float(‘0.‘+decimal)
s1 = str(bin(integer))[2:]
if decimal == 0:
return s1
l2 = ‘‘
count = 32
while (count > 0):
count = count - 1
decimal = decimal * 2
if decimal >= 1:
l2 += ‘1‘
decimal -= 1
if decimal == 0:
return s1 + ‘.‘ + l2
else:
l2 += ‘0‘
return ‘ERROR‘
https://www.jiuzhang.com/solution/binary-representation/#tag-highlight-lang-python
[Lintcode]180. Binary Representation
原文:https://www.cnblogs.com/siriusli/p/10359355.html