166. Fraction to Recurring Decimal
给定表示分数的分子和分母的两个整数,返回字符串格式的分数。
如果小数部分重复,则将重复部分括在括号内。
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)".
解题思路
为了将结果变为字符串格式,同时判断是否是循环小数,需要进行循环的整除。
每次整除之前,判断被除数是否出现过,若出现过,按要求加括号,否则,把被除数与对应的位置(用于可能的加括号时确定位置)这个数对保存。
为使效率较好,使用哈希存储,在python中为字典。
注意:判断分子、分母的正负
程序代码
class Solution:
def fractionToDecimal(self, numerator, denominator):
"""
:type numerator: int
:type denominator: int
:rtype: str
"""
flag = numerator * denominator < 0 #异号结果为负,flag置1
numerator, denominator = abs(numerator), abs(denominator)#取绝对值
a = numerator // denominator
remain = numerator % denominator
if not remain: return str(a) if not flag else ('-' + str(a))#计算整数部分
res = str(a) + '.'
numerator = remain * 10
dic = {}
while(numerator):
if numerator in dic.keys(): #判断被除数是否出现过
res = res[0:dic[numerator]] + '(' + res[dic[numerator]:] + ')'
return res if not flag else ('-' + res)
else:
dic[numerator] = len(res)#添加数对
a = numerator // denominator #计算商、余数
remain = numerator % denominator
res += str(a)
if not remain: return res if not flag else ('-' + res)#若除尽
numerator = remain * 10