LintCode Q180 Binary Representation in Python

  • Jinhai ZHOU
  • 7 Minutes
  • 2017年1月9日
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
51
52
53
54
55
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 len(n) == 0:
return
sign = False
if n[0] == '-':
sign = True
n = n[1:]
if '.' in n:
[inte, frac] = n.split('.')
frac_bin = self.binaryFraction(frac)
if frac_bin == 'ERROR':
return 'ERROR'
inte_bin = self.binaryInteger(inte)
if len(frac_bin) > 0:
inte_bin.append('.')
inte_bin.extend(frac_bin)
res = ('').join(inte_bin)
if sign:
return '-' + res
else:
return res
else:
return ('').join(self.binaryInteger(n))
def binaryInteger(self, inte):
# integer part
inte = int(inte)
inte_bin = []
if inte == 0:
return ['0']
while inte != 0:
inte_bin.append(str(inte%2))
inte /= 2
inte_bin = inte_bin[::-1]
return inte_bin
def binaryFraction(self, frac):
# fraction part
frac = float('0.' + frac)
frac_len = 0
frac_bin = []
while frac != 0 and frac_len < 32:
frac_bin.append(str(int(frac*2)))
if frac*2 >= 1:
frac = frac*2 - 1
else:
frac = frac*2
frac_len += 1
if frac_len == 32:
return 'ERROR'
return frac_bin
知识共享许可协议
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。