-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy path166_Fraction_to_Recurring_Decimal.py
More file actions
35 lines (33 loc) · 1.06 KB
/
166_Fraction_to_Recurring_Decimal.py
File metadata and controls
35 lines (33 loc) · 1.06 KB
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
class Solution(object):
def fractionToDecimal(self, numerator, denominator):
"""
:type numerator: int
:type denominator: int
:rtype: str
"""
if numerator == 0:
return '0'
fraction = ''
if (numerator < 0) ^ (denominator < 0):
fraction += '-'
dividend = abs(numerator)
divisor = abs(denominator)
fraction += str(dividend / divisor)
remainder = dividend % divisor
if remainder == 0:
return fraction
fraction += '.'
dic = {}
while remainder != 0:
if remainder in dic:
fraction = fraction[:dic[remainder]] + '(' + fraction[dic[remainder]:] + ')'
break
dic[remainder] = len(fraction)
remainder *= 10
fraction += str(remainder / divisor)
remainder %= divisor
return fraction
if __name__ == '__main__':
s = Solution()
# print s.longestValidParentheses(")(((((()())()()))()(()))(")
print s.fractionToDecimal(-50, 8)