Leetcode:Question12--Integer to Roman

题目描述

Leetcode:Question12--Integer to Roman

题目分析

首先熟悉转换规则,然后可以使用两个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

也可以不采用数组的方法,直接采用条件判断来做,不过代码会写的很多,而且没什么必要

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