11# Time: O(logn), where logn is the length of result strings
22# Space: O(1)
3- #
4- # Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.
3+
4+ # Given two integers representing the numerator and denominator of a fraction,
5+ # return the fraction in string format.
56#
67# If the fractional part is repeating, enclose the repeating part in parentheses.
78#
1011# Given numerator = 1, denominator = 2, return "0.5".
1112# Given numerator = 2, denominator = 1, return "2".
1213# Given numerator = 2, denominator = 3, return "0.(6)".
13- #
1414
15- class Solution :
16- # @return a string
15+ class Solution (object ):
1716 def fractionToDecimal (self , numerator , denominator ):
17+ """
18+ :type numerator: int
19+ :type denominator: int
20+ :rtype: str
21+ """
1822 dvd , dvs = abs (numerator ), abs (denominator )
19- integer , decimal , dict = "" , "" , {}
20-
21- if dvd > dvs :
22- integer = str (dvd / dvs )
23- dvd %= dvs
24- else :
25- integer = "0"
26-
23+ result , lookup = "" , {}
24+ if (numerator > 0 and denominator < 0 ) or (numerator < 0 and denominator > 0 ):
25+ result = "-"
26+ result += str (dvd / dvs )
27+ dvd %= dvs
28+
2729 if dvd > 0 :
28- integer += "."
30+ result += "."
2931
30- idx = 0
31- while dvd :
32- if dvd in dict :
33- decimal = decimal [:dict [dvd ]] + "(" + decimal [dict [dvd ]:] + ")"
34- break
35-
36- dict [dvd ] = idx
37- idx += 1
38-
32+ while dvd and dvd not in lookup :
33+ lookup [dvd ] = len (result )
3934 dvd *= 10
40- decimal += str (dvd / dvs )
35+ result += str (dvd / dvs )
4136 dvd %= dvs
42-
43- if (numerator > 0 and denominator < 0 ) or (numerator < 0 and denominator > 0 ):
44- return "-" + integer + decimal
45- else :
46- return integer + decimal
37+
38+ if dvd in lookup :
39+ result = result [:lookup [dvd ]] + "(" + result [lookup [dvd ]:] + ")"
40+
41+ return result
42+
4743
4844if __name__ == "__main__" :
4945 print Solution ().fractionToDecimal (1 , 9 )
5046 print Solution ().fractionToDecimal (- 50 , 8 )
5147 print Solution ().fractionToDecimal (22 , 2 )
52- print Solution ().fractionToDecimal (- 22 , - 2 )
48+ print Solution ().fractionToDecimal (- 22 , - 2 )
0 commit comments