leetcode之12.整数转罗马数字python实现

12.整数转罗马数字

class Solution(object):
    def intToRoman(self, num):
        """
        :type num: int
        :rtype: str
        """
        lookup = {
            'M': 1000, 
            'CM': 900, 
            'D': 500, 
            'CD': 400, 
            'C': 100, 
            'XC': 90, 
            'L': 50, 
            'XL': 40, 
            'X': 10, 
            'IX': 9, 
            'V': 5, 
            'IV': 4, 
            'I': 1
        }
        roman = ''
        for symbol, val in sorted(lookup.items(), key = lambda t: t[1])[::-1]:
            
        	while num >= val:
        		roman += symbol
        		num -= val
        return roman

使用sorted(lookup.items(), key = lambda t: t[1])[::-1]的原因是为了避免出现IIII的情况

你可能感兴趣的:(leetcode之12.整数转罗马数字python实现)