【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      
相关推荐
文丑颜不良啊15 小时前
LeetCode2221~2240题目解析
java·leetcode
Navigator_Z16 小时前
LeetCode //C - 1317. Convert Integer to the Sum of Two No-Zero Integers
c语言·算法·leetcode
文丑颜不良啊17 小时前
LeetCode2161~2180题目解析
java·leetcode
文丑颜不良啊19 小时前
LeetCode2141~2160题目解析
java·leetcode
Dream it possible!1 天前
LeetCode 面试经典 150_多维动态规划_交错字符串(97_C++_中等)
算法·leetcode·面试·动态规划
心抵鹊1 天前
算法之双指针系列(一)
算法·leetcode
Pniubi2 天前
力扣560.和为k的子数组
算法·leetcode·职场和发展
Pniubi2 天前
力扣438.找到字符串中所有字母异位词
算法·leetcode·职场和发展
文丑颜不良啊2 天前
LeetCode2081~2100题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode2061~2080题目解析
java·leetcode