[leetcode]166. Fraction to Recurring Decimal

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 class Solution(object):
 2     def fractionToDecimal(self, numerator, denominator):
 3         n,remainder = divmod(abs(numerator),abs(denominator))
 4         flag = '-' if numerator*denominator<0 else ''
 5         res = [flag+str(n),'.']
 6         s = []
 7         while remainder not in s:
 8             s.append(remainder)
 9             n,remainder = divmod(remainder*10,abs(denominator))
10             res.append(str(n))
11         i = s.index(remainder)
12         res.insert(i+2,'(')
13         res.append(')')
14         return ''.join(res).replace('(0)','').rstrip('.')
15         
原文地址:https://www.cnblogs.com/fcyworld/p/6504208.html