力扣练习之分数到小数

我爱海鲸 2023-05-26 00:03:05 暂无标签

简介中级算法、数学

原题出处:https://leetcode.cn/leetbook/read/top-interview-questions-medium/xwm8ne/

解法一:

class Solution:
    def fractionToDecimal(self, numerator: int, denominator: int) -> str:
        if numerator == 0:
            return "0"
        res = ""
        if (numerator < 0) ^ (denominator < 0):
            res += "-"
        numerator, denominator = abs(numerator), abs(denominator)
        res += str(numerator // denominator)
        remainder = numerator % denominator
        if remainder == 0:
            return res
        res += "."
        hash_map = {}
        while remainder != 0:
            if remainder in hash_map:
                res = res[:hash_map[remainder]] + "(" + res[hash_map[remainder]:] + ")"
                break
            hash_map[remainder] = len(res)
            remainder *= 10
            res += str(remainder // denominator)
            remainder %= denominator
        return res

思路:

长除法,同时用哈希表来记录小数部分是否出现过以及它们在结果中的位置。

可以用 -1 来表示循环小数出现的位置还没有记录过,用 -2 来表示正在记录循环小数。

小数点的位置是整除后余数不为 0 的位置。当余数出现循环时,从哈希表中取出该余数出现的位置,加上括号后即可得到结果。

你好:我的2025