File tree Expand file tree Collapse file tree 1 file changed +57
-0
lines changed
Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Original file line number Diff line number Diff line change 1+ # -*- coding: utf-8 -*-
2+
3+ class Solution :
4+ #@param n: Given a decimal number that is passed in as a string
5+ #@return: A string
6+ def binaryRepresentation (self , n ):
7+ # write you code here
8+ # TODO: 添加注释
9+ bin_val = []
10+ int_digits = 0
11+ for i in xrange (len (n )):
12+ if n [i ] != '.' :
13+ int_digits += 1
14+ else :
15+ break
16+ int_part = self .int (n , 0 , int_digits )
17+ float_part = self .int (n , int_digits + 1 , len (n ))
18+ if int_part == 0 :
19+ bin_val .append ('0' )
20+ else :
21+ while int_part != 0 :
22+ bin_val .append ('1' if (int_part % 2 ) == 1 else '0' )
23+ int_part /= 2
24+ bin_val .reverse ()
25+ if float_part > 0 :
26+ bin_val .append ('.' )
27+ bin_float_digits = 0
28+ adjust = 0
29+ while ((int_digits + 1 + adjust ) < len (n )) and (n [int_digits + 1 + adjust ] == '0' ):
30+ adjust += 1
31+ round_up = self .roundUp (float_part , adjust )
32+ while float_part > 0 :
33+ float_part_2 = float_part * 2
34+ bin_val .append ('1' if float_part_2 >= round_up else '0' )
35+ bin_float_digits += 1
36+ if bin_float_digits > 32 :
37+ return 'ERROR'
38+ float_part = (float_part_2 - round_up ) if float_part_2 >= round_up else float_part_2
39+ return '' .join (bin_val )
40+
41+ def int (self , number , start , end ): # 字符串转整数
42+ ret = 0
43+ while start < end :
44+ ret = ret * 10 + int (number [start ])
45+ start += 1
46+ return ret
47+
48+ def roundUp (self , val , adjust ): # 向上取整
49+ ret = 1
50+ while val > 0 :
51+ ret *= 10
52+ val /= 10
53+ i = 0
54+ while i < adjust :
55+ ret *= 10
56+ i += 1
57+ return ret
You can’t perform that action at this time.
0 commit comments