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”.
Solution
Convert Int part to HEX from right to left: integer = 5
digit = integer % 2
integer = integer / 2
Convert Decimal part to HEX from left to right: e.g. decimal = 0.5 -> 0.1 (hex)
digit = int(decimal * 2)
if decimal * 2 >= 1.0, then decimal = decimal * 2 - 1.0
classSolution:#@param n: Given a decimal number that is passed in as a string#@return: A stringdefbinaryRepresentation(self,n):# write you code here# write you code hereresult=""integer=0decimal=0ifn==None:returnresult# Parse the integer and decimaldot_index=n.find(".")left=n[0:dot_index]right=n[dot_index+1:len(n)]ifleft!=Noneandleft!='0':integer=int(left)ifright!=Noneandright!='0':decimal=int(right)# Translate to hex# int partifinteger==0:result="0"else:whileinteger!=0:digit=integer%2result=str(digit)+resultinteger=integer/2integer_len=len(result)# decimal part# eg. 5.0ifdecimal==0:returnresultelse:result+="."decimal=float("0."+right)whiledecimal!=0.0:digit=int(decimal*2)result=result+str(digit)# decimal can only be 32bit at mostiflen(result)-integer_len>=32:return"ERROR"ifdecimal*2>=1.0:decimal=decimal*2-1.0else:decimal=decimal*2returnresult