【LeetCode 12】整数转罗马数字

如果这题按照正向的求解则非常麻烦。例如对于3749这个数字,你需要判断是千分位,还是百分位,还是十分位,还是个位?然后再判断数字大小进行组合,这么一通操作下来非常繁琐。但如果采取逆向思维解题,即按照从大到小的顺序将所有的组成成分排序,这样就能直接映射出答案了。这题背后有贪心的味道。

1. 题目

2. 分析

3. 代码

python 复制代码
class Solution:
    def intToRoman(self, num: int) -> str:
        num2roman = {1:"I", 4:"IV", 5:"V", 9:"IX", 10:"X", 40: "XL", 50:"L", 90:"XC", 100:"C", 400:"CD", 500:"D", 900:"CM", 1000:"M"}
        components = list(num2roman.keys())
        components.sort() # 从小到大的排序

        res = ""
        for i in reversed(components):
            while num >= i:
                res += num2roman[i]
                num -= i
        return res      
相关推荐
CoderYanger21 分钟前
A.每日一题——2536. 子矩阵元素加 1
java·线性代数·算法·leetcode·矩阵
倦王2 小时前
力扣日刷251117
算法·leetcode·职场和发展
Swift社区7 小时前
LeetCode 427 - 建立四叉树
算法·leetcode·职场和发展
墨染点香8 小时前
LeetCode 刷题【160. 相交链表】
算法·leetcode·链表
少睡点觉8 小时前
LeetCode 238. 除自身以外数组的乘积 问题分析+解析
java·算法·leetcode
YoungHong19928 小时前
面试经典150题[066]:分隔链表(LeetCode 86)
leetcode·链表·面试
Wenhao.11 小时前
LeetCode 救生艇
算法·leetcode·golang
夏鹏今天学习了吗11 小时前
【LeetCode热题100(69/100)】字符串解码
linux·算法·leetcode
小白程序员成长日记11 小时前
2025.11.18 力扣每日一题
算法·leetcode·职场和发展
未若君雅裁13 小时前
LeetCode 18 - 四数之和 详解笔记
java·数据结构·笔记·算法·leetcode