Question: https://leetcode.com/problems/fraction-to-recurring-decimal/
Question Name: Fraction to Recurring Decimal
Again, a little mathematical puzzle. Pay attention to some corner cases.
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 | 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) |