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)
相关推荐
浩少7022 小时前
LeetCode-17day:贪心算法
算法·leetcode·贪心算法
weixin_516875652 小时前
力扣 30 天 JavaScript 挑战 第37天 第九题笔记 知识点: 剩余参数,拓展运算符
javascript·笔记·leetcode
测试19983 小时前
Web自动化测试:测试用例流程设计
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
山烛8 小时前
矿物分类系统开发笔记(一):数据预处理
人工智能·python·机器学习·矿物分类
集成显卡14 小时前
使用 Google 开源 AI 工具 LangExtract 进行结构化信息抽取
python·google·openai
久笙&15 小时前
对象存储解决方案:MinIO 的架构与代码实战
数据库·python·架构
爱coding的橙子15 小时前
每日算法刷题Day63:8.19:leetcode 堆6道题,用时1h50min
算法·leetcode·职场和发展
不甘懦弱15 小时前
阿里云搭建flask服务器
服务器·python·flask
岁忧15 小时前
(nice!!!)(LeetCode 每日一题) 1277. 统计全为 1 的正方形子矩阵 (动态规划)
java·c++·算法·leetcode·矩阵·go·动态规划
赵英英俊15 小时前
Python day51
人工智能·pytorch·python