Python easy to understand solution with comments.

  • 2

    These code is mainly based on the idea described here (, while the "dictionary" part is a little bit different from the C++ version. The main idea for this question is quite straightforward , while clean, accepted code is not so easy to write, especially at the first time.

    def fractionToDecimal(self, numerator, denominator):
        num, den = numerator, denominator
        if not den:  # denominator is 0
        if not num:  # numerator is 0
            return "0"
        res = []
        if (num < 0) ^ (den < 0):
            res.append("-")  # add the sign
        num, den = abs(num), abs(den)
        rmd = num % den
        if not rmd:
            return "".join(res)  # only has integral part
        res.append(".")  # has frational part
        dic = {}
        while rmd:
            if rmd in dic:   # the remainder recurs
                res.insert(dic[rmd], "(")
            dic[rmd] = len(res) 
            div, rmd = divmod(rmd*10, den)
        return "".join(res)

Log in to reply

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