题目
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)”.
题目要求
求分数的小数表示。
解题思路
本题参考书影博客的解题思路。
要考虑两点:
当余数出现重复时,说明分数的小数表示有循环存在,用字典记录每个余数第一次出现的位置。
循环结束标志:余数为0,或者出现重复的余数。
代码
class Solution(object):
def fractionToDecimal(self, numerator, denominator):
"""
:type numerator: int
:type denominator: int
:rtype: str
"""
negativeSign = numerator * denominator < 0
numerator = abs(numerator)
denominator = abs(denominator)
numslist = []
loopDict = {}
cnt = 0
loopStr = None
while True:
numslist.append(str(numerator / denominator))
cnt += 1
numerator = 10 * (numerator % denominator)
if numerator == 0:
break
loc = loopDict.get(numerator)
if loc:
loopStr = ''.join(numslist[loc:cnt])
break
loopDict[numerator] = cnt
ans = numslist[0]
if len(numslist) > 1:
ans += '.'
if loopStr:
ans += ''.join(numslist[1:len(numslist) - len(loopStr)]) + '(' + ''.join(numslist[len(numslist) - len(loopStr):]) + ')'
else:
ans += ''.join(numslist[1:])
if negativeSign:
ans = '-' + ans
return ans