180. Binary Representation
- 本题难度: Hard
- Topic: Bit Manipulation
Description
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
思路
- 出错 注意字符串转化成整数/小数的方式