My python Solution


  • 0
    A

    I'm a newbie to python. Any comments and improvements are welcome.

    class Solution:
    # @return a string
    def fractionToDecimal(self, numerator, denominator):
        if denominator == 0:
            raise 
        elif numerator == 0:
            return "0"
        elif numerator*denominator < 0:
            if numerator<0:
                return "-" + self.fractionToDecimal(-numerator,denominator)
            else:
                return "-" + self.fractionToDecimal(numerator,-denominator)
        else:
            if numerator < 0:
                return self.fractionToDecimal(-numerator,-denominator)
            else:
                if numerator<denominator:
                    return "0" + convert(numerator,denominator)
                else:
                    return convert(numerator,denominator)
    
    def convert(numerator,denominator):
    if numerator >= denominator:
        temp = numerator // denominator
        remainder = numerator%denominator
        return str(temp) + convert(remainder,denominator)
    else:
        remainder = numerator
        L = []
        string = "."
        pos = None
        if remainder == 0:
            return ""
        else:
            stop = False
        while not stop:
            L.append(remainder)
            remainder = remainder*10
            temp = remainder // denominator
            string = string+str(temp)
            
            remainder = remainder % denominator # new remainder
            if remainder == 0:
                stop = True
            else:
                if remainder in L:
                    pos = L.index(remainder)
                    stop = True
        if pos != None:
            return string[:pos+1] + "(" + string[pos+1:] + ")"
        else:
            return string

Log in to reply
 

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