Binary Representation

Question

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".

Thoughts

参考

这一题基本上就是个数学问题,分为整数部分和小数部分来解

如果没有小数部分,直接整数部分解 如果有,就分为两个部分

整数

将整数转换为2进制, 这里用到的方法是不断地将N/2,并将n%2的结果加到string的前面

小数

将小数转换为2进制,采用的是不断乘以2的方法

这部分数学问题要复习一下

Solution

class Solution:
    #@param n: Given a decimal number that is passed in as a string
    #@return: A string
    def binaryRepresentation(self, n):
        # write you code here
        if "." not in n:
            return self.parseInteger(n)
        params = n.split(".")
        frac = self.parseFloat(params[1])
        if frac == "ERROR":
            return frac
        if frac == "0" or frac == "":
            return self.parseInteger(params[0])

        return self.parseInteger(params[0]) + "." + frac

    def parseInteger(self, s):
        if s == "" or s == "0":
            return "0"
        n = int(s)
        result = ""
        while n:
            result = str(n % 2) + result
            n = n / 2

        return result

    def parseFloat(self, s):
        result = ""
        f = float("0." + s)
        dic = {}
        while f:
            if len(result) > 32 or f in dic:
                return "ERROR"
            dic[f] = True
            f = f * 2
            if f >= 1:
                result += "1"
                f -= 1
            else:
                result += "0"

        return result