Skip to content

Commit baadf4e

Browse files
committed
166
1 parent 4ed2d98 commit baadf4e

File tree

6 files changed

+51
-0
lines changed

6 files changed

+51
-0
lines changed
File renamed without changes.
File renamed without changes.
File renamed without changes.
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
class Solution(object):
2+
def fractionToDecimal(self, numerator, denominator):
3+
"""
4+
:type numerator: int
5+
:type denominator: int
6+
:rtype: str
7+
"""
8+
if denominator==0:
9+
raise Exception("Div by Zero")
10+
if numerator==0:
11+
return "0"
12+
neg = (numerator<0) and (denominator>0) or (numerator>0) and (denominator<0)
13+
14+
n = abs(numerator)
15+
d = abs(denominator)
16+
17+
if n%d==0:
18+
result = str(n/d)
19+
else:
20+
result = str(n/d)+"."
21+
n = n%d
22+
digits = []
23+
visited = {n:0}
24+
loop_from = -1
25+
while True:
26+
n = n*10
27+
digit = n/d
28+
n = n%d
29+
30+
if n in visited:
31+
digits.append(digit)
32+
loop_from = visited[n]
33+
break
34+
else:
35+
digits.append(digit)
36+
visited[n] = len(digits)
37+
38+
if n==0:
39+
break
40+
print digits
41+
if loop_from<0:
42+
suffix = ''.join([str(d) for d in digits])
43+
else:
44+
first = ''.join([str(d) for d in digits[:loop_from]])
45+
second = "("+''.join([str(d) for d in digits[loop_from:]])+")"
46+
suffix = first+second
47+
result += suffix
48+
49+
if neg:
50+
return "-"+result
51+
return result

0 commit comments

Comments
 (0)