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)

 

上一篇:AtCoder Beginner Contest 166 题解


下一篇:166.Fraction to Recurring Decimal