Python | Leetcode Python题解之第166题分数到小数

题目:

题解:

python 复制代码
class Solution:
    def fractionToDecimal(self, numerator: int, denominator: int) -> str:
        if numerator % denominator == 0:
            return str(numerator // denominator)

        s = []
        if (numerator < 0) != (denominator < 0):
            s.append('-')

        # 整数部分
        numerator = abs(numerator)
        denominator = abs(denominator)
        integerPart = numerator // denominator
        s.append(str(integerPart))
        s.append('.')

        # 小数部分
        indexMap = {}
        remainder = numerator % denominator
        while remainder and remainder not in indexMap:
            indexMap[remainder] = len(s)
            remainder *= 10
            s.append(str(remainder // denominator))
            remainder %= denominator
        if remainder:  # 有循环节
            insertIndex = indexMap[remainder]
            s.insert(insertIndex, '(')
            s.append(')')

        return ''.join(s)
相关推荐
weixin_457760006 分钟前
PIL库将图片位深度是1、8、32统一转换为24的方法
python
Lucky高1 小时前
Pandas库入门
python·pandas
小鸡吃米…1 小时前
Python PyQt6教程三-菜单与工具栏
开发语言·python
sin_hielo2 小时前
leetcode 2110
数据结构·算法·leetcode
Jack电子实验室2 小时前
【杭电HDU】校园网(DeepL/Srun)自动登录教程
python·嵌入式硬件·计算机网络·自动化
木头左2 小时前
二值化近似计算在量化交易策略中降低遗忘门运算复杂度
python
Jelena157795857922 小时前
Java爬虫淘宝拍立淘item_search_img拍接口示例代码
开发语言·python
郝学胜-神的一滴2 小时前
Python数据模型:深入解析及其对Python生态的影响
开发语言·网络·python·程序人生·性能优化
麦格芬2303 小时前
LeetCode 763 划分字母区间
算法·leetcode·职场和发展
free-elcmacom3 小时前
机器学习进阶<8>PCA主成分分析
人工智能·python·机器学习·pca