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)
相关推荐
小镇学者15 小时前
【python】python虚拟环境与pycharmIDE配置
开发语言·python
会员果汁15 小时前
leetcode-887. 鸡蛋掉落-C
c语言·算法·leetcode
q_354888515315 小时前
交通数据分析项目:python地铁数据可视化分析系统 Flask框架 爬虫 数据分析 轨道数据 地铁数据分析 大数据 (源码)✅
人工智能·爬虫·python·机器学习·信息可视化·数据分析·flask
夏鹏今天学习了吗1 天前
【LeetCode热题100(87/100)】最小路径和
算法·leetcode·职场和发展
幻云20101 天前
Python深度学习:从筑基到登仙
前端·javascript·vue.js·人工智能·python
仰望星空@脚踏实地1 天前
本地Python脚本是否存在命令注入风险
python·datakit·命令注入
LOnghas12111 天前
果园环境中道路与树木结构检测的YOLO11-Faster语义分割方法
python
Lips6111 天前
2026.1.20力扣刷题笔记
笔记·算法·leetcode
鱼跃鹰飞1 天前
Leetcode347:前K个高频元素
数据结构·算法·leetcode·面试
2501_944526421 天前
Flutter for OpenHarmony 万能游戏库App实战 - 蜘蛛纸牌游戏实现
android·java·python·flutter·游戏