面试150 整数转罗马数字

面试150 整数转罗马数字_第1张图片

思路

建立数字和字符的字典映射表,遍历映射表做差,将字符添加到结果中,当差为0的时候,break退出循环。返回最后的结果output

class Solution:
    def intToRoman(self, num: int) -> str:
        if num<1:
            return ''
        num_to_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')]
        output=[]
        for key,val in num_to_map:
            while num>=key:
                num-=key
                output.append(val)
            if num==0:
                break
        return ''.join(output)

你可能感兴趣的:(面试150题目,面试,leetcode,python,字符串)