其他分享
首页 > 其他分享> > leetcode-166-分数到小数

leetcode-166-分数到小数

作者:互联网

题目描述:

方法一:

class Solution:
    def fractionToDecimal(self, numerator: int, denominator: int) -> str:
        if numerator == 0:
            return "0"
        res = []
        if (numerator > 0) ^ (denominator > 0):
            res.append("-")
        numerator = abs(numerator)
        denominator = abs(denominator)
        trading = numerator // denominator
        res.append(str(trading))
        num = numerator % denominator
        if num == 0: return "".join(res)
        res.append(".")
        lookup = {num: len(res)}
        while num != 0:
            num *= 10
            res.append(str(num // denominator))
            num %= denominator
            if num in lookup:
                idx = lookup[num]
                res.insert(idx, "(")
                res.append(")")
                break
            else:
                lookup[num] = len(res)
        # print(res)
        return "".join(res)

 

标签:res,denominator,numerator,num,lookup,166,leetcode,append,小数
来源: https://www.cnblogs.com/oldby/p/11207248.html