题目:
将罗马数字转为整数形式。
解题思路:
首先需要知道罗马数字的表示方式及读取方式。表示方式如字典所示dict_roman = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}。读取方式从左到右依次读取,若当前的数字大于上一个数字,则加上这个数字并减去上一个数字的两倍,否则直接加上这个数字
代码(python):
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
dict_roman = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
output = dict_roman[s[0]]
for i in range(len(s)-1):
if dict_roman[s[i+1]]>dict_roman[s[i]]:
output = output+dict_roman[s[i+1]]-2*dict_roman[s[i]]
else:
output = output+dict_roman[s[i+1]]
return output