【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      
相关推荐
Nil2087 分钟前
leetcode 54螺旋矩阵
算法·leetcode·矩阵
evans在进步5 小时前
LeetCode 394:字符串解码——Java 单栈模拟与嵌套解析详解
java·python·leetcode
Nil2086 小时前
leetcode 189轮转数组
数据结构·算法·leetcode
吃着火锅x唱着歌6 小时前
LeetCode 3885.设计事件管理器
算法·leetcode·职场和发展
土司大王7 小时前
LeetCode hto100——字母异位词分组
java·算法·leetcode
土司大王8 小时前
LeetCode hot100——两数之和
数据结构·算法·leetcode
Navigator_Z9 小时前
LeetCode //C - 1200. Minimum Absolute Difference
c语言·算法·leetcode
wabs6669 小时前
关于字符串【力扣344.反转字符串的思考】
数据结构·算法·leetcode
Nil20810 小时前
leetcode 73矩阵置0
算法·leetcode·矩阵
旖旎夜光12 小时前
LeetCode 1658:将 x 减到 0 的最小操作数(滑动窗口) —— 题解
数据结构·c++·算法·leetcode·滑动窗口