mycode   73.92%

如何判断同号? 1)res = "-" if ((numerator>0) ^ (denominator>0)) else ""   2)如下

class Solution(object):
    def fractionToDecimal(self, numerator, denominator):
        """
        :type numerator: int
        :type denominator: int
        :rtype: str
        """
        if denominator == 0: return None
        if numerator == 0 :return '0'
        positive = '' if (numerator< 0) is (denominator < 0) else '-'
        numerator = abs(numerator) if numerator < 0 else numerator
        denominator = abs(denominator) if denominator < 0 else denominator
        ans = ''
        res = numerator // denominator
        add = numerator % denominator
        ans += str(res)
        if add == 0:
            return positive+ans
        ans += '.'
        repeat = []
        while True:
            res = add*10 // denominator
            add = add*10 % denominator
            if (res,add) in repeat:
                pos = repeat.index((res,add))
                for i,item in enumerate(repeat):
                    if i==pos:
                        ans += '('
                    ans += str(item[0])
                ans += ')'           
                return positive+ans
            else:
                repeat.append((res,add))
                if add == 0:
                    for i,item in enumerate(repeat):
                        ans += str(item[0])
                    return positive+ans
            

 参考:

思路; 我记录了每次的商和余数,其实没必要啦,只需要记录余数即可,因为除数是不变的,余数重复出现了,自然商也就重复啦

class Solution(object):
    def fractionToDecimal(self, numerator, denominator):
        """
        :type numerator: int
        :type denominator: int
        :rtype: str
        """
    
        def div(d,p):
            x = d//p
            y = d - (x*p )
            return (x,y)
        if numerator == 0: return "0"
        res = "-" if ((numerator>0) ^ (denominator>0)) else ""
        numerator,denominator = abs(numerator),abs(denominator)
        x ,y = div(numerator,denominator)     
        if y == 0:
            return res + str(x)
        x,y,denominator = abs(x),abs(y),abs(denominator)
        
        res += str(x) + "."
        dic = {}
        dic[y] = len(res)
        while y:
            y *= 10
            x ,y = div(y , denominator)
            res += str(x)
            if y in dic:
                pos = dic[y]
                res = res[:pos] + '(' + res[pos:]+')'
                break
            else:
                dic[y] = len(res)
        return res