Leetcode 12.整数转罗马数字 Python

class Solution:
    def intToRoman(self, num):
        m=num//1000
        y=num%1000
        d=y//500
        y=y%500
        c=y//100
        y=y%100
        l=y//50
        y=y%50
        x=y//10
        y=y%10
        v=y//5
        i=y%5
        result="M"*m+"D"*d+"C"*c+"L"*l+"X"*x+"V"*v+"I"*i
        replace=[["VIIII","IX"],["IIII","IV"],["LXXXX","XC"],["XXXX","XL"],
        ["DCCCC","CM"],["CCCC","CD"]]
        for rep in replace:
            result=result.replace(rep[0],rep[1])
        return result

解题思路:

首先,通过多次的取整和取余得出MDCLXVI这7中字母出现的次数

然后排列起来

处理特殊情况4、9、40、90、400、900

最后返回得出的罗马数字


关注我,在Leetcode专栏中查看更多题目的解题思路吧!

你可能感兴趣的:(Leetcode,leetcode,python,算法)