罗马数字与整数相互转化

leetcode中的题目

直接上代码:

 1 def int2roman(num):
 2     ret = ""
 3     lists = (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1)
 4     chars = ("M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I")
 5     while num > 0:
 6         i = 0
 7         while i <= 12:
 8             if lists[i] <= num:
 9                 break
10             i += 1
11         ret += chars[i]
12         num -= lists[i]
13     return ret
14 
15 def int2roman2(num):
16     M = ("", "M", "MM", "MMM")
17     C = ("","C","CC","CCC","CD","D","DC","DCC","DCCC","CM")
18     X = ("","X","XX","XXX","XL","L","LX","LXX","LXXX","XC")
19     I = ("","I","II","III","IV","V","VI","VII","VIII","IX")
20     return M[(num/1000)%10]+C[(num/100)%10]+X[(num/10)%10]+I[num%10]

上面是整数转罗马数字的,第一种方法是把所有可能的字符表示出来,然后1-3999的数字是由其相加组成的,依次从最大的先加上去,懂得原理会比较好理解;

第二中是将每一位的可能表示出来,直接算出每一位再替换上去,也比较简单。

下面是罗马数字转整数:

 1 def roman2int(s):
 2     mapval = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
 3     cur = 0
 4     pre = 1001
 5     ret = 0
 6     for i in s:
 7         ret += mapval[i]
 8         cur = mapval[i]
 9         if pre < cur:
10             ret -= 2 * pre
11         pre = cur
12     return ret

前面的数字比后面的数字小是减法,比如IV = 5 - 1

先把所有的数字加起来,如果有前面比后面小的就减去自己的两倍即可。

 

posted @ 2016-10-18 22:49  george_cw  阅读(1011)  评论(0编辑  收藏  举报