-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfraction-to-recurring-decimal.py
More file actions
41 lines (41 loc) · 1.12 KB
/
fraction-to-recurring-decimal.py
File metadata and controls
41 lines (41 loc) · 1.12 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
class Solution(object):
def fractionToDecimal(self, numerator, denominator):
"""
:type numerator: int
:type denominator: int
:rtype: str
"""
neg = numerator / denominator < 0
if numerator < 0:
numerator = -numerator
if denominator < 0:
denominator = -denominator
ans = str(numerator / denominator)
if neg:
ans = '-' + ans
if numerator % denominator == 0:
return ans
ans += '.'
remain = numerator % denominator
s = ''
loop = True
remains = {remain: 0}
i = 0
split = 0
while True:
i += 1
c = str(remain * 10 / denominator)
remain = remain * 10 % denominator
s += c
if remain in remains:
split = remains[remain]
break
remains[remain] = i
if remain == 0:
loop = False
break
if loop:
ans += s[:split] + '(' + s[split:] + ')'
else:
ans += s
return ans