Fast and concise python solution using dictionary.


  • 6
    T
    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)

  • 1

    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.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.