LeetCode题目以及答案(4)
程序员文章站
2024-03-22 14:38:40
...
(1)题目:罗马数字转整数
规则:
字符 数值 I 1 V 5 X 10 L 50 C 100 D 500 M 1000
注意:(1)小的数字(限于 Ⅰ、X 和 C)在大的数字的左边,所表示的数等于大数减小数得到的数,如 IV=5,IX=9,XL=40,XC=90,CD=400,CM=900
(2)不能有超过连续的三个相同的罗马数字排列一起;在一个数的上面画一条横线,表示这个数增值 1,000 倍。
#!/usr/bin/env python
#encoding:utf-8
"""
__author__:adam
功能:罗马数字转换阿拉伯数字
"""
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
sum=0
convert={'M': 1000,'D': 500 ,'C': 100,'L': 50,'X': 10,'V': 5,'I': 1}
for i in range(len(s)-1):
if convert[s[i]] >= convert[s[i+1]]:
sum = sum + convert[s[i]]
else:
sum = sum - convert[s[i]]
return sum + convert[s[-1]]
data = Solution()
list1 = ['III','IV','IX','LVIII','MCMXCIV']
for i in list1:
print i,
print data.romanToInt(i)
print '\n'
>>>
=============== RESTART: C:/Users/20525/Desktop/romanToInt.py ===============
III 3
IV 4
IX 9
LVIII 58
MCMXCIV 1994
>>>
(2)整数转换罗马数字
#!/usr/bin/env python
#encoding:utf-8
"""
__author__:adam
功能:罗马数字转换阿拉伯数字
=================整数转换成罗马数字============================
"""
class Solution(object):
def IntToroman(self,num):
"""
:type num:int
:rtype:str
"""
list_num = [1000,900,500,400,100,90,50,40,10,9,5,4,1]
#之间对应的罗马数字如下
list_str = ["M","CM","D","CD","C","XC","L","XL","X","IX","V",'IV','I']
#放置一个空的变量
one_str = ' '
for i in range(len(list_num)):
while num >= list_num[i]:
num = num - list_num[i]
one_str = one_str + list_str[i]
return one_str
data = Solution()
list1 = [1994,58,9,4,3]
for i in list1:
print i, ":" ,data.IntToroman(i)
print '\n'
>>>
=============== RESTART: C:/Users/20525/Desktop/romanToInt.py ===============
1994 : MCMXCIV
58 : LVIII
9 : IX
4 : IV
3 : III
>>>