【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      
相关推荐
TracyCoder1231 小时前
LeetCode Hot100(50/100)——153. 寻找旋转排序数组中的最小值
算法·leetcode·职场和发展
化学在逃硬闯CS1 小时前
Leetcode110.平衡二叉树
数据结构·c++·算法·leetcode
爱coding的橙子1 小时前
Day87:2.12:leetcode 动态规划8道题,用时3h
算法·leetcode·动态规划
努力学算法的蒟蒻2 小时前
day84(2.12)——leetcode面试经典150
算法·leetcode·面试
程序员酥皮蛋2 小时前
hot 100 第二十三题 23.反转链表
数据结构·算法·leetcode·链表
TracyCoder1233 小时前
LeetCode Hot100(51/100)——155. 最小栈
数据结构·算法·leetcode
Y.O.U..3 小时前
力扣刷题-86.分隔链表
算法·leetcode·链表
TracyCoder1233 小时前
LeetCode Hot100(52/100)——394. 字符串解码
算法·leetcode·职场和发展
thginWalker3 小时前
leetcode有空可以挑战的题目
leetcode
52Hz1183 小时前
力扣207.课程表、208.实现Trie(前缀树)
python·leetcode