forked from yingl/LintCodeInPython
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_representation.py
More file actions
Latest commit
57 lines (54 loc) · 1.82 KB
/
Copy pathbinary_representation.py
File metadata and controls
57 lines (54 loc) · 1.82 KB
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
56
57
# -*- coding: utf-8 -*-
classSolution:
#@param n: Given a decimal number that is passed in as a string
#@return: A string
defbinaryRepresentation(self, n):
# write you code here
# TODO: 添加注释
bin_val= []
int_digits=0
foriinxrange(len(n)):
ifn[i] !='.':
int_digits+=1
else:
break
int_part=self.int(n, 0, int_digits)
float_part=self.int(n, int_digits+1, len(n))
ifint_part==0:
bin_val.append('0')
else:
whileint_part!=0:
bin_val.append('1'if (int_part%2) ==1else'0')
int_part/=2
bin_val.reverse()
iffloat_part>0:
bin_val.append('.')
bin_float_digits=0
adjust=0
while ((int_digits+1+adjust) <len(n)) and (n[int_digits+1+adjust] =='0'):
adjust+=1
round_up=self.roundUp(float_part, adjust)
whilefloat_part>0:
float_part_2=float_part*2
bin_val.append('1'iffloat_part_2>=round_upelse'0')
bin_float_digits+=1
ifbin_float_digits>32:
return'ERROR'
float_part= (float_part_2-round_up) iffloat_part_2>=round_upelsefloat_part_2
return''.join(bin_val)
defint(self, number, start, end): # 字符串转整数
ret=0
whilestart<end:
ret=ret*10+int(number[start])
start+=1
returnret
defroundUp(self, val, adjust): # 向上取整
ret=1
whileval>0:
ret*=10
val/=10
i=0
whilei<adjust:
ret*=10
i+=1
returnret