leetcode166. 分数到小数

给定两个整数,分别表示分数的分子 numerator 和分母 denominator,以字符串形式返回小数。

如果小数部分为循环小数,则将循环的部分括在括号内。
示例 1:
输入: numerator = 1, denominator = 2
输出: “0.5”
示例 2:
输入: numerator = 2, denominator = 1
输出: “2”
示例 3:
输入: numerator = 2, denominator = 3
输出: "0.(6)"

1.先判断符号;2.再处理整数部分;3.用一个dict记录除数是否出现过来找循环起始点:

class Solution:
    def fractionToDecimal(self, numerator: int, denominator: int) -> str:
        res = []
        if numerator*denominator < 0:  # 先判断符号
            res.append('-')
        numerator, denominator = abs(numerator), abs(denominator)
        int_part = numerator // denominator
        res.append(str(int_part))
        remainder = numerator % denominator
        if not remainder:
            return ''.join(res)
        else:
            remainder = remainder*10
            res.append('.')
        records = {}  # 记录除数是否出现过
        while True:
            int_part, left = remainder // denominator, remainder % denominator
            if remainder in records:  # 注意这里是除数
                circle_index = records[remainder]  # 循环起始点
                return ''.join(res[:circle_index])+'('+''.join(res[circle_index:])+')'
            records[remainder] = len(res)
            if remainder == 0:  # 如果余数为0说明除尽了
                return ''.join(res)
            res.append(str(int_part))  # 注意要后加
            remainder = left*10

你可能感兴趣的:(LeetCode,Python,leetcode)