Short python solution


  • -2
    F
    class Solution(object):
    def fractionToDecimal(self, numerator, denominator):
        n, d=numerator, denominator
        flag=n*d>0
        n, d=abs(n), abs(d)
        if n==0 or d==0: return '0'
        if n%d==0: return str(n/d) if flag else '-'+str(n/d)
        res, dic=str(n/d)+'.', collections.defaultdict(int)
        pos=len(res)
        n%=d
        while n:
            if dic[n]: 
                res=res[:dic[n]]+'('+res[dic[n]:]+')'
                break
            dic[n]=pos
            pos+=1
            res+=str(n*10/d)
            n=n*10%d
        return res if flag else '-'+res

Log in to reply
 

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