1+ '''
2+ Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.
3+
4+ If the fractional part is repeating, enclose the repeating part in parentheses.
5+
6+ For example,
7+
8+ Given numerator = 1, denominator = 2, return "0.5".
9+ Given numerator = 2, denominator = 1, return "2".
10+ Given numerator = 2, denominator = 3, return "0.(6)".
11+ Hint:
12+
13+ No scary math, just apply elementary math knowledge. Still remember how to perform a long division?
14+ Try a long division on 4/9, the repeating part is obvious. Now try 4/333. Do you see a pattern?
15+ Be wary of edge cases! List out as many test cases as you can think of and test your code thoroughly.
16+ '''
17+
18+ class Solution (object ):
19+ def fractionToDecimal (self , numerator , denominator ):
20+ """
21+ :type numerator: int
22+ :type denominator: int
23+ :rtype: str
24+ """
25+ sign = '-' if numerator * denominator < 0 else ''
26+ quotient , remainder = divmod (abs (numerator ), abs (denominator ))
27+ result_list = [sign , str (quotient ), '.' ]
28+ remainders = []
29+ while remainder not in remainders :
30+ remainders .append (remainder )
31+ quotient , remainder = divmod (remainder * 10 , abs (denominator ))
32+ result_list .append (str (quotient ))
33+
34+ idx = remainders .index (remainder )
35+ result_list .insert (idx + 3 , '(' )
36+ result_list .append (')' )
37+ result = '' .join (result_list ).replace ('(0)' , '' ).rstrip ('.' )
38+ return result
39+
40+
41+ if __name__ == "__main__" :
42+ assert Solution ().fractionToDecimal (1 , 2 ) == '0.5'
43+ assert Solution ().fractionToDecimal (2 , 1 ) == '2'
44+ assert Solution ().fractionToDecimal (2 , 3 ) == '0.(6)'
0 commit comments