Problem: Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

Solution: Roman to Integer, Python:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# @Date : 2015-01-07 03:12:45
# @Author : NSSimacer
# @Version : 1.0
class Solution:
# @return an integer
def romanToInt(self, s):
dic = {
'I': lambda i: -1 if s[i + 1] in ['V', 'X'] else 1,
'X': lambda i: -10 if s[i + 1] in ['L', 'C'] else 10,
'C': lambda i: -100 if s[i + 1] in ['D', 'M'] else 100,
'V': lambda i: 5,
'L': lambda i: 50,
'D': lambda i: 500,
'M': lambda i: 1000,
}
result = 0
s += '$' # 需要统计到最后一个字符,防止越界,在字符串后面添加额外字符
for i, ch in enumerate(s[:]):
result += dic[ch](i)
return result

附:罗马数字拼写规则