Python solution


  • 0
    H
    class Solution(object):
        def fractionToDecimal(self, numerator, denominator):
            """
            :type numerator: int
            :type denominator: int
            :rtype: str
            """
            num,dem=numerator, denominator
            '''
            a,b=num,dem
            a,b=abs(a),abs(b)
            a,b=max(a,b),min(a,b)
            while b:
                r=a%b
                a=b
                b=r
            gcd=a
            num/=gcd
            dem/=gcd
            '''
            if num*dem<0:
                return '-'+self.fractionToDecimal(abs(num),abs(dem))
            ans=str(num/dem)
            if num%dem:
                ans+='.'
                n,d=num,dem
                quo=n/d
                n-=quo*d
                n*=10
                nprevs=[]
                while n%d:
                    nprevs.append(n)
                    quo=n/d
                    n-=quo*d
                    n*=10
                    ans+=str(quo)
                    if n in nprevs:
                        i=len(nprevs)-nprevs.index(n)
                        rep=ans[-i:]
                        ans=ans[:-i]+'(%s)'%rep
                        return ans
                ans+=str(n/d)
            return ans

  • 0
    P

    Here is my solution in Python as well. Running time is 40ms. Cannot get it shorter :-(

    class Solution(object):
        def fractionToDecimal(self, numerator, denominator):
            """
            :type numerator: int
            :type denominator: int
            :rtype: str
            """
            if numerator>0 and denominator<0 or numerator<0 and denominator>0:
                ans = "-"
            else:
                ans = ""
            numerator,denominator = abs(numerator),abs(denominator)
            ans += str(numerator//denominator)
            numerator %= denominator
            if numerator == 0:
                return ans
            ans += "."    
            prevNumerators = {}
            while numerator not in prevNumerators:
                prevNumerators[numerator] = len(ans)
                if numerator == 0:
                    return ans
                else:
                    ans += str(10*numerator//denominator)
                    numerator = 10*numerator % denominator
            patternStartIndex = prevNumerators[numerator]
            return ans[:patternStartIndex]+"("+ans[patternStartIndex:]+")"

Log in to reply
 

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