【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      
相关推荐
Tisfy23 分钟前
LeetCode 3121.统计特殊字母的数量 II:状态机
算法·leetcode·题解·状态机
洛水水26 分钟前
【力扣100题】61.和为 K 的子数组
算法·leetcode·哈希算法
sheeta199830 分钟前
LeetCode 补拙笔记 日期:2026.05.27 题目:61. 旋转链表
笔记·leetcode·链表
过期动态14 小时前
【LeetCode 热题 100】移动零
java·数据结构·算法·leetcode·职场和发展·rabbitmq
菜菜的顾清寒16 小时前
力扣HOT100(32)二叉树的中序遍历
数据结构·算法·leetcode
csdn_aspnet17 小时前
java 算法 LeetCode 编号 70 - 爬楼梯
java·开发语言·算法·leetcode
_日拱一卒18 小时前
LeetCode:200岛屿数量
算法·leetcode·职场和发展
圣保罗的大教堂19 小时前
leetcode 153. 寻找旋转排序数组中的最小值 中等
leetcode
csdn_aspnet19 小时前
C语言 算法 LeetCode 编号 70 - 爬楼梯
c语言·开发语言·算法·leetcode
菜菜的顾清寒19 小时前
力扣HOT100(31)K 个一组翻转链表
算法·leetcode·链表