【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      
相关推荐
Ch_ty1 小时前
leetcode解题思路分析(一百六十八)1452 - 1458 题
算法·leetcode·哈希算法
pilgrim5310 小时前
结合 Leetcode 题探究KMP算法
算法·leetcode
前进的李工13 小时前
LeetCode hot100:234 回文链表:快慢指针巧判回文链表
python·算法·leetcode·链表·快慢指针·回文链表
sin_hielo13 小时前
leetcode 3228
算法·leetcode
xier_ran14 小时前
力扣(LeetCode)100题:41.缺失的第一个正数
数据结构·算法·leetcode
Swift社区15 小时前
LeetCode 425 - 单词方块
算法·leetcode·职场和发展
Miraitowa_cheems16 小时前
LeetCode算法日记 - Day 104: 通配符匹配
linux·数据结构·算法·leetcode·深度优先·动态规划
不穿格子的程序员19 小时前
从零开始写算法——二分-搜索二维矩阵
线性代数·算法·leetcode·矩阵·二分查找
Kuo-Teng20 小时前
LeetCode 19: Remove Nth Node From End of List
java·数据结构·算法·leetcode·链表·职场和发展·list
Kuo-Teng20 小时前
LeetCode 21: Merge Two Sorted Lists
java·算法·leetcode·链表·职场和发展