# # 【LeetCode】166. Fraction to Recurring Decimal 解题报告（Python）

## # 题目描述：

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:

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

Example 2:

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

Example 3:

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

## # 解题方法

``````class Solution:
def fractionToDecimal(self, numerator, denominator):
"""
:type numerator: int
:type denominator: int
:rtype: str
"""
d = dict()
div, mod = self.divmod(numerator, denominator)
if mod == 0:
return str(div)
ans = "-" if ((numerator > 0) ^ (denominator > 0)) else ""
div, mod, denominator = abs(div), abs(mod), abs(denominator)
ans += str(div) + "."
d[mod] = len(ans)
while mod:
mod *= 10
div, mod = self.divmod(mod, denominator)
ans += str(div)
if mod in d:
index = d[mod]
ans = ans[:index] + "(" + ans[index:] + ")"
break
else:
d[mod] = len(ans)
return ans

def divmod(self, a, b):
q = int(a / b)   # I'm using 3.x
r = a - b * q
return (q, r)
``````

``````class Solution:
def fractionToDecimal(self, numerator, denominator):
"""
:type numerator: int
:type denominator: int
:rtype: str
"""
if numerator == 0: return "0"
d = dict()
ans = "-" if ((numerator > 0) ^ (denominator > 0)) else ""
numerator, denominator = abs(numerator), abs(denominator)
div, mod = divmod(numerator, denominator)
if mod == 0: return ans + str(div)
ans += str(div) + "."
d[mod] = len(ans)
while mod:
mod *= 10
div, mod = divmod(mod, denominator)
ans += str(div)
if mod in d:
index = d[mod]
ans = ans[:index] + "(" + ans[index:] + ")"
break
else:
d[mod] = len(ans)
return ans
``````

## # 日期

2018 年 9 月 8 日 ———— 美好的周末，从刷题开始