Simple Python code as elementary student did


  • 0
    W
    class Solution(object):
        def fractionToDecimal(self, numerator, denominator):
            """
            :type numerator: int
            :type denominator: int
            :rtype: str
            """
    
            q=[]
            p=[]
            sign=0
            if (numerator<0 and denominator>0) or (numerator>0 and denominator<0)  :
                sign=1
                numerator=max( numerator, -1*numerator)
                denominator=max(denominator,-1*denominator)
            while str(numerator%denominator) not in p and str(numerator%denominator) !=0:
                q.append(str(numerator/denominator))
                p.append(str(numerator%denominator))
                numerator=10*(numerator%denominator)
                
            if numerator%denominator==0:
                if len(q)>1:
                    re= q[0]+'.'+''.join(q[1:])
                else:
                    re= q[0]
            elif str(numerator%denominator) in p:
                q.append(str(numerator/denominator))
                p.append(str(numerator%denominator))
                n=p.index(str(numerator%denominator))
                
                if n>=1:
                    re= q[0]+'.'+''.join(q[1:n+1])+'('+''.join(q[n+1:])+')'
                if n==0:
                    re= q[0]+'.'+'('+''.join(q[1:])+')'
            if sign==1:
                re="-"+re
            return re
    
     Two arrays, one is result, the other is remainder.

Log in to reply
 

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