Given integers representing the numerator and denominator of a fraction, return the fraction in string format.
If the fractional part was 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:typ E denominator:int:rtype:str "" "negative = False if numerator*denominator<0: Negative = True N,m = ABS (numerator), ABS (denominator) A = n//m if a==n/m: if negative: Return '-' +str (a) Else:return str (a) temp = [] res = [] n = n% m while True:temp.append (n) n *= res.append (str (n//m)) n = n%m If N==0:if negative:return '-' + str (a) + '. ' + '. Join (RES) ELS E:return Str (a) + '. ' + '. Join (RES) if n in temp:if negative: Return '-' + str (a) + '. ' + '. Join (Res[:temp.index (n)]) + ' (' + '. Join (Res[temp.index (n):]) + ') ' Else Return Str (a) + '. ' + '. Join (Res[:temp.index (n)]) + ' (' + '. Join (Res[temp.index (n):]) + ') '
The first idea is to find the circulation body from the quotient, so the problem is that it is difficult to judge the length of the loop body and the position of the beginning. But if you use division, it's easy to find the loop body from the dividend.
166. Fraction to recurring Decimal