Given two integers , Molecules representing fractions respectively numerator
Denominator denominator
, With Returns a decimal as a string .
If the decimal part is a circular decimal , The loop is enclosed in brackets .
If there are multiple answers , Just go back Any one .
For all given inputs , Guarantee The length of the answer string is less than 104
.
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)"
Example 4:
Input :numerator = 4, denominator = 333 Output :"0.(012)"
Example 5:
Input :numerator = 1, denominator = 5 Output :"0.2"
Tips :
-2^31 <= numerator, denominator <= 2^31 - 1
denominator != 0
class Solution(object):
def fractionToDecimal(self, numerator, denominator):
if numerator < 0 and denominator < 0:
numerator, denominator = -numerator, -denominator
u = (numerator < 0) ^ (denominator < 0)
numerator = abs(numerator)
denominator = abs(denominator)
numerator = numerator % denominator
if numerator == 0:
return str(numerator // denominator)
s = str(abs(numerator) // denominator) + "."
q = {}
l = []
while numerator < denominator:
numerator = numerator * 10
l.append(numerator)
q[numerator] = numerator // denominator
numerator = numerator % denominator * 10
while numerator not in q and numerator != 0:
l.append(numerator)
q[numerator] = numerator // denominator
numerator = numerator % denominator
numerator = numerator * 10
for i in range(0, len(l)):
if numerator == l[i]:
s = s + "("
s = s + str(q[l[i]])
if "(" in s:
s = s + ")"
if u:
s = "-" + s
return s