题目:

【leetcode系列】【py3】【中等】整数转罗马数字

原题链接: https://leetcode-cn.com/problems/integer-to-roman/

 

解题思路:

贪心算法

建立映射表,数字从大到小的计算每个字符的个数

 

代码实现:

class Solution:
    def intToRoman(self, num: int) -> str:
        val_map = {1000 : 'M', 900 : 'CM', 500 : 'D', 400 : 'CD', 100 : 'C', 90 : 'XC', 50 : 'L', 40 : 'XL', 10 : 'X', 9 : 'IX', 5 : 'V', 4 : 'IV', 1 : 'I'}
        
        s = []
        for key in val_map:
            s.append(val_map[key] * (num // key))
            num = num % key
            
        return ''.join(s)

相关文章:

  • 2021-09-11
  • 2021-12-15
  • 2021-10-17
  • 2021-08-07
  • 2021-12-25
  • 2022-02-11
  • 2022-01-14
  • 2021-12-24
猜你喜欢
  • 2021-12-31
  • 2021-11-28
  • 2022-01-17
  • 2021-11-26
  • 2021-11-02
  • 2021-08-31
  • 2021-07-09
相关资源
相似解决方案