def fractionToDecimal(self, numerator, denominator):
sign = '' if numerator * denominator < 0 else ''
head, remainder = divmod(abs(numerator), abs(denominator))
tail, seen = '', {}
while remainder != 0:
if remainder in seen:
tail = tail[: seen[remainder]] + '(' + tail[seen[remainder]:] + ')'
break
seen[remainder] = len(tail)
digit, remainder = divmod( remainder*10, abs(denominator) )
tail+=str(digit)
return sign + str(head) + (tail and '.' + tail)
Fast and concise python solution using dictionary.


Hmm, I didn't know that repeated
stringvar += character
is fast. For appending n characters, I thought it would only be O(n^2), but apparently it is O(n) thanks to some optimization. Good to know.