Integer to Roman - LeetCode

来源:互联网 发布:网络舆情软件 编辑:程序博客网 时间:2024/06/06 04:40

Integer to Roman - LeetCode

题目:

Given an integer, convert it to a roman numeral.

Input is guaranteed to be within the range from 1 to 3999.


分析:

这道题目里面的罗马数字含义在Roman to Integer - LeetCode里面有解释,我把里面的对应图拿过来。

基本字符
I
V
X
L
C
D
M
相应的阿拉伯数字表示为
1
5
10
50
100
500
1000
我们发现,(I,V,X)和 (X,L,C) 和 (C,D,M) 都差了10倍,而我们在以前使用的多数都是1-9的罗马数字:['I','II','III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX'],那这样的话我们可以发现,1000内的数字,百位,十位,个位之间的差别只是把字符变一下,其他的顺序没有变化,例如代表9的的IX,而代表90的是LC,只是对应位置的字符变了,所以我们可以这样:一开始循环数字,一个1000多一个M,控制数字到1000内后,通过循环的每一次模运算,我们只是替换1-9对应数字的字符,加到res里,最后我们把一开始的M(如果有的话)和res里的字符组合,就是最后答案。

代码:

class Solution:    # @return a string    def intToRoman(self, num):        rep = [['I','V','X'],['X','L','C'],['C','D','M']]        dic = ['I','II','III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX']        res = []        da1000 = ''        i = 0        while num >= 1000: # 大于1000时我们扣掉大于1000的部分                da1000 += 'M'                num -= 1000        while num != 0:            temp = num%10            num = num/10            if temp == 0:                i += 1                continue            res.append(dic[temp-1].replace('X',rep[i][2]).replace('V',rep[i][1]).replace('I',rep[i][0])) #替换掉对应位置的字符            i +=1        return da1000+''.join(res[::-1])                                                                                     


0 0