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)
相关推荐
J***79399 分钟前
Python在机器学习中的数据处理
开发语言·python·机器学习
深蓝电商API24 分钟前
初级爬虫反爬应对:解决 403、IP 限制的简单方法
爬虫·python
闲人编程1 小时前
Python协程的演进:从yield到async/await的完整历史
java·前端·python·async·yield·await·codecapsule
睿思达DBA_WGX1 小时前
使用 Python 的第三方库 xlrd 读取 Excel 文件
python·excel
做怪小疯子1 小时前
LeetCode 热题 100——链表——相交链表
算法·leetcode·链表
大佬,救命!!!1 小时前
python实现五子棋
开发语言·python·个人开发·pygame·少儿编程·五子棋
while(努力):进步2 小时前
5G与物联网:连接万物的数字化未来
leetcode
明知道的博客4 小时前
解决WSL环境下DeepSeek-OCR运行时内存不足问题
python·ocr·deepseek·deepseek-ocr
2501_941804324 小时前
C++在高性能互联网服务开发与系统优化中的应用与实战经验解析
leetcode
FreeCode5 小时前
LangGraph1.0智能体开发:Graph API概念与设计
python·langchain·agent