Leetcode(13) Roman to Integer

Description:

Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.

解法:

我们只要考虑两种情况即可:

第一,如果当前数字是最后一个数字,或者之后的数字比它小的话,则加上当前数字

第二,其他情况则减去这个数字

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
d = {'I': 1 , 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D' : 500, 'M': 1000};
res = 0;
for i in range(len(s)):
val = d[s[i]];
if(i == len(s) - 1 or d[s[i]]>=d[s[i+1]]):
res += val;
else:
res-=val;
return res;