forked from luliyucoordinate/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0166.py
37 lines (32 loc) · 846 Bytes
/
0166.py
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
class Solution:
def fractionToDecimal(self, n, d):
"""
:type numerator: int
:type denominator: int
:rtype: str
"""
flag = True
if n < 0:
flag = not flag
n = -n
if d < 0:
flag = not flag
d = -d
res = str(n // d)
n %= d
if n == 0:
if not flag and res != "0":
return "-" + res
return res
res += '.'
m = dict()
while n:
if n in m:
res = res[0:m[n]] + "(" + res[m[n]:] + ")"
break
else:
m[n] = len(res)
n *= 10
res += str(n // d)
n %= d
return res if flag else "-" + res