forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
fraction-to-recurring-decimal.py
51 lines (42 loc) · 1.46 KB
/
fraction-to-recurring-decimal.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
from __future__ import print_function
# Time: O(logn), where logn is the length of result strings
# Space: O(1)
# 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)".
class Solution(object):
def fractionToDecimal(self, numerator, denominator):
"""
:type numerator: int
:type denominator: int
:rtype: str
"""
result = ""
if (numerator > 0 and denominator < 0) or (numerator < 0 and denominator > 0):
result = "-"
dvd, dvs = abs(numerator), abs(denominator)
result += str(dvd / dvs)
dvd %= dvs
if dvd > 0:
result += "."
lookup = {}
while dvd and dvd not in lookup:
lookup[dvd] = len(result)
dvd *= 10
result += str(dvd / dvs)
dvd %= dvs
if dvd in lookup:
result = result[:lookup[dvd]] + "(" + result[lookup[dvd]:] + ")"
return result
if __name__ == "__main__":
print(Solution().fractionToDecimal(1, 9))
print(Solution().fractionToDecimal(-50, 8))
print(Solution().fractionToDecimal(22, 2))
print(Solution().fractionToDecimal(-22, -2))