罗马数字与整数相互转化

Posted 这么近_那么远

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了罗马数字与整数相互转化相关的知识,希望对你有一定的参考价值。

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

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

 

以上是关于罗马数字与整数相互转化的主要内容,如果未能解决你的问题,请参考以下文章

阿拉伯数字与中文数字的转换----------相互转化

C code 字符串与整数的相互转化

阿拉伯数字与中文数字的转换----------相互转化

C/C++中字符串与数字相互转换

阿拉伯数字与中文数字的转换----------相互转化

用C语言递归法将一个整数化为字符串