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)
相关推荐
ZhengEnCi2 小时前
M3-markconv库找不到wkhtmltopdf问题
python
2301_764441335 小时前
LISA时空跃迁分析,地理时空分析
数据结构·python·算法
Billlly6 小时前
ABC 453 个人题解
算法·题解·atcoder
chushiyunen6 小时前
python rest请求、requests
开发语言·python
cTz6FE7gA6 小时前
Python异步编程:从协程到Asyncio的底层揭秘
python
baidu_huihui6 小时前
在 CentOS 9 上安装 pip(Python 的包管理工具)
开发语言·python·pip
南 阳6 小时前
Python从入门到精通day63
开发语言·python
lbb 小魔仙6 小时前
Python_RAG知识库问答系统实战指南
开发语言·python
FreakStudio7 小时前
MicroPython LVGL基础知识和概念:底层渲染与性能优化
python·单片机·嵌入式·电子diy