Python solution


  • 9
    Y
    class Solution:
    # @return a string
    def fractionToDecimal(self, numerator, denominator):
        res=""
        if numerator/denominator<0:
            res+="-"
        if numerator%denominator==0:
            return str(numerator/denominator)
        numerator=abs(numerator)
        denominator=abs(denominator)
        res+=str(numerator/denominator)
        res+="."
        numerator%=denominator
        i=len(res)
        table={}
        while numerator!=0:
            if numerator not in table.keys():
                table[numerator]=i
            else:
                i=table[numerator]
                res=res[:i]+"("+res[i:]+")"
                return res
            numerator=numerator*10
            res+=str(numerator/denominator)
            numerator%=denominator
            i+=1
        return res
    

    Idea is to put every remainder into the hash table as a key, and the current length of the result string as the value. When the same remainder shows again, it's circulating from the index of the value in the table.


  • 0

    I like this solution
    very clean and readable


  • 0
    X

    It should be if rather than elif in line 7 right?


  • 0
    Y

    @xinlin5 yes, you are right. Thanks for pointing it out.


Log in to reply
 

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