leetcode 166. 分数到小数

题目链接:leetcode

思路:

  • 不存在循环小数
  • 存在循环小数,形如1.2(3456)
  • 存在循环小数,形如1.(3456)
  • 使用字典存储余数mod,每次循环更新余数,如果字典中存在,说明循环了,再构造字符串
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
class Solution(object):
def fractionToDecimal(self, numerator, denominator):
"""
:type numerator: int
:type denominator: int
:rtype: str
"""
prefix = '-' if numerator*denominator < 0 else ''
numerator = abs(numerator)
denominator = abs(denominator)
divide = numerator//denominator
mod = numerator%denominator
if mod == 0:return prefix+str(divide)
d = {}
stack = []
i = -1
while True:
if mod == 0:
return prefix+str(divide)+'.'+''.join(stack)
mod *= 10
i += 1
if mod in d:
idx = d[mod]
return prefix+str(divide)+'.'+''.join(stack[:idx])+'('+''.join(stack[idx:])+')'

if mod < denominator:
stack.append('0')
d[mod] = i
else:
stack.append(str(mod//denominator))
d[mod] = i
mod = mod%denominator