Fraction to Recurring Decimal
franklinqin0 Hash TableMathString
# Solution
# HashMap
class Solution:
def fractionToDecimal(self, numerator: int, denominator: int) -> str:
if numerator == 0:
return "0"
res = []
if (numerator < 0) != (denominator < 0):
res.append("-")
n = abs(numerator)
d = abs(denominator)
# calc the integer part
res.append(str(n // d))
r = n % d
if r == 0:
return "".join(res)
# n = r
res.append(".")
hashmap = {}
while r != 0:
if r in hashmap:
res.insert(hashmap[r], "(")
# div =
res.append(")")
break
hashmap[r] = len(res)
r *= 10
res.append(str(r // d))
r %= d
return "".join(res)
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
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