class Solution:
# @return a string
def fractionToDecimal(self, numerator, denominator):
# Adjust the sign of the input.
sign = ""
if numerator < 0 and denominator > 0:
numerator = -numerator
sign = "-"
if numerator > 0 and denominator < 0:
denominator = -denominator
sign = "-"
# Check the case when numerator is divisible by denominator
remaining = numerator % denominator
if remaining == 0: return sign + str(numerator // denominator)
# Process the fractional part. It is a mathematical story: balala...
result = [sign, str(numerator // denominator), "."]
position = {} # A dictionary of dictionary
current = 3
while remaining != 0:
remaining *= 10
newvalue = remaining // denominator
if not newvalue in position: position[newvalue] = {}
newRemaining = remaining % denominator
if newRemaining == 0:
# Division finished.
result.append(str(newvalue))
break
elif newRemaining in position[newvalue]:
# Loop is found.
result.insert(position[newvalue][newRemaining], "(")
result.append(")")
break
result.append(str(newvalue))
position[newvalue][newRemaining] = current
# Prepare the next digit.
remaining = remaining % denominator
current += 1
return "".join(result)