Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
把给定的罗马数字转成阿拉伯数字~先科普一下,罗马数字对于每个位有三个单位:1,5,10,对于1到9,表示方法如下:1-3:用1表示;4:1:5左边加一个1;5: 直接用5表示; 6-8: 5右边加相应的1;9: 10左边加一个1~所以,右边比左边大(pre > cur)就减对应值,否则就加对应值
class Solution:
# @return an integer
def romanToInt(self, s):
roman_dict = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
res = pre = 0
for c in reversed(s):
cur = roman_dict[c]
if cur >= pre:
res += cur
else:
res -= cur
pre = cur
return res