Simple python solution with a hash table


  • 0
    N
    class Solution(object):
        def fractionToDecimal(self, numerator, denominator):
            """
            :type numerator: int
            :type denominator: int
            :rtype: str
            """
            map = {}
            d, r = divmod(abs(numerator), abs(denominator))
            s = ""
            if numerator * denominator < 0:
                s = "-"
            s += str(d)
            if r is 0:
                return s
            s += "."
            deno = abs(denominator)
            i = len(s)
            while r is not 0:
                map[r] = i
                r *= 10
                d, r = divmod(r, deno)
                s += str(d)
                if r is not 0 and r in map:
                    ind = map[r]
                    return s[:ind] + "(" + s[ind:i+1] + ")"
                i += 1
            return s
    

Log in to reply
 

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