Short Python beats 97%


  • 0

    Here I used a dictionary seen to keep track of the index for every remainder remain we have met. Once we meet a remainder we've met before, we know we find a circle.

    class Solution(object):
        def fractionToDecimal(self, numerator, denominator):
            """
            :type numerator: int
            :type denominator: int
            :rtype: str
            """
            negative, ans = "-" if numerator * denominator < 0 else "", []
            INT, remain = divmod(abs(numerator), abs(denominator))
            if not remain: return negative + str(INT)
            
            ans.extend([negative, str(INT), "."])
            seen, i, den = {}, len(ans), abs(denominator)
            while remain:
                if remain in seen:
                    return "".join(ans[:seen[remain]]) + "(" + \
                           "".join(ans[seen[remain]:]) + ")"
                seen[remain] = i
                INT, remain = divmod(remain * 10, den)
                ans.append(str(INT))
                i += 1
            return "".join(ans)
    

Log in to reply
 

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