卖萌的弱渣

I am stupid, I am hungry.

Binary Representation

Binary Representation

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
    1. digit = integer % 2
    2. integer = integer / 2
  • Convert Decimal part to HEX from left to right: e.g. decimal = 0.5 -> 0.1 (hex)
    1. digit = int(decimal * 2)
    2. if decimal * 2 >= 1.0, then decimal = decimal * 2 - 1.0
    3. if decimal * 2 < 1.0, then decimal = decimal * 2
  • If decimal part’s hex is > 32bit, return ERROR
(Binary-Representation.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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
        # write you code here
        result = ""
        integer = 0
        decimal = 0
        if n==None:
            return result
        # Parse the integer and decimal
        dot_index = n.find(".")
        left = n[0:dot_index]
        right = n[dot_index+1:len(n)]
        if left!=None and left!='0':
            integer = int(left)
        if right!=None and right!='0':
            decimal = int(right)

        # Translate to hex
        # int part
        if integer == 0:
            result = "0"
        else:
            while integer!=0:
                digit = integer%2
                result = str(digit) + result
                integer = integer/2

        integer_len = len(result)

        # decimal part
        # eg. 5.0
        if decimal == 0:
            return result
        else:
            result += "."
            decimal = float("0."+right)
            while decimal!=0.0:
                digit = int(decimal*2)
                result = result+str(digit)
                # decimal can only be 32bit at most
                if len(result)-integer_len >= 32:
                    return "ERROR"
                if decimal*2 >= 1.0:
                    decimal = decimal*2 - 1.0
                else:
                    decimal = decimal*2
        return result