166. fraction to recurring decimal 解法

166. Fraction to Recurring Decimal

Difficulty: Medium

Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.

If the fractional part is repeating, enclose the repeating part in parentheses.

Example 1:

1
2
Input: numerator = 1, denominator = 2
Output: "0.5"

Example 2:

1
2
Input: numerator = 2, denominator = 1
Output: "2"

Example 3:

1
2
Input: numerator = 2, denominator = 3
Output: "0.(6)"

解法

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
class :
def fractionToDecimal(self, num: int, denom: int) -> str:
tag = -1 if num * denom < 0 else 1
num, denom = abs(num), abs(denom)
re_num = ''
# 字典记录由该余数算出的下一个商value在re_num中的位置(从0开始),如果有循环节的话,循环节刚好就是从重复余数的字典值对应的下标处开始的。
dic = {}
while 1:
if not re_num:#首次进行计算

value = num // denom
num = num % denom
re_num += str(value)

if num == 0:#无循环
return re_num if tag == 1 else '-' + re_num
else:
re_num += '.'
dic[str(num)] = len(re_num)
else: #后续计算,即寻找循环项,若没有,直接return
num *= 10
value = num // denom
num = num % denom
re_num += str(value)

if num == 0:#无循环
return re_num if tag == 1 else '-' + re_num
else:#有循环时返回
if str(num) in dic:
re_num = re_num[:dic[str(num)]] + '(' + re_num[dic[str(num)]:] + ')'
return re_num if tag == 1 else '-' + re_num
else:
dic[str(num)] = len(re_num)