## 题目描述：

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.

For example,

• Given numerator = 1, denominator = 2, return "0.5".
• Given numerator = 2, denominator = 1, return "2".
• Given numerator = 2, denominator = 3, return "0.(6)".

## 题目大意：

• 给定分子 = 1, 分母 = 2, 返回 "0.5".
• 给定分子 = 2, 分母 = 1, 返回 "2".
• 给定分子 = 2, 分母 = 3, 返回 "0.(6)".

## 解题思路：

``````    0.16
6 ) 1.00
0
1 0       <-- Remainder=1, mark 1 as seen at position=0.
- 6
40      <-- Remainder=4, mark 4 as seen at position=1.
- 36
4      <-- Remainder=4 was seen before at position=1, so the fractional part which is 16 starts repeating at position=1 => 1(6).
``````

## Python代码(Accepted 108ms)：

``````class Solution:
# @return a string
def fractionToDecimal(self, numerator, denominator):
negativeFlag = numerator * denominator < 0
numerator = abs(numerator)
denominator = abs(denominator)
numList = []
cnt = 0
loopDict = dict()
loopStr = None
while True:
numList.append(str(numerator / denominator))
cnt += 1
numerator = 10 * (numerator % denominator)
if numerator == 0:
break
loc = loopDict.get(numerator)
if loc:
loopStr = "".join(numList[loc:cnt])
break
loopDict[numerator] = cnt
ans = numList[0]
if len(numList) > 1:
ans += "."
if loopStr:
ans += "".join(numList[1:len(numList) - len(loopStr)]) + "(" + loopStr + ")"
else:
ans += "".join(numList[1:])
if negativeFlag:
ans = "-" + ans
return ans
``````

Pingbacks已关闭。

1. 每天签到就送钱 发布于 2014年12月19日 00:42 #

不错不错[嘻嘻]