LeetCode12. 整数转罗马数字

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Jaster_wisdom/article/details/80657171

题目大意:将一个1到3999范围内的整数转为罗马数字

题目分析:首先熟悉转换规则,然后可以使用两个list存储对应的映射关系,然后每次从大到小看num是否大于1000,大于900,大于500,若在某个区间的话,就将罗马数字加进来,num减去相应的数值,直到num为0

代码展示:

class Solution(object):
    def intToRoman(self, num):
        intForm = [1000,900,500,400,100,90,50,40,10,9,5,4,1]
        romanForm = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"]
        string = ""
        while num!=0:
            for i in range(0,len(intForm)):
                if num>=intForm[i]:
                    string += romanForm[i]
                    num -= intForm[i]
                    break
        return string

方法二:不使用两个数组来保存对应关系,使用if else的结构,只是逻辑上稍微复杂一点。

代码展示:

class Solution(object):
    def intToRoman(self, num):
        result = []
        while num!=0:
            num = self.transform(result,num)
        string = ""
        for i in range(0,len(result)):
            string += result[i]
        return string
    
    def transform(self,result,num):
        if num>=1000:
            result.append('M')
            num -= 1000
        elif num>=900:
            result.append("CM")
            num -= 900
        elif num>=500:
            result.append('D')
            num -= 500
        elif num>=400:
            result.append("CD")
            num -= 400
        elif num>=100:
            result.append('C')
            num -= 100
        elif num>=90:
            result.append("XC")
            num -= 90
        elif num>=50:
            result.append('L')
            num -= 50
        elif num>=40:
            result.append("XL")
            num -= 40
        elif num>=10:
            result.append('X')
            num -= 10
        elif num>=9:
            result.append("IX")
            num -= 9
        elif num>=5:
            result.append('V')
            num -= 5
        elif num>=4:
            result.append("IV")
            num -= 4
        else:
            result.append('I')
            num -= 1
        return num

展开阅读全文

没有更多推荐了,返回首页