13 roman to integer

Description

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

1
2
3
4
5
6
7
8
Symbol       Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000

For example, two is written as II in Roman numeral, just two one’s added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:
I can be placed before V (5) and X (10) to make 4 and 9.
X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (1000) to make 400 and 900.
Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.

My Solution

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class (object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
result = 0
jump = False
for index, char in enumerate(s):
if jump:
jump = False
continue
if char == 'I':
result = result + 1
if index < len(s)-1:
if s[index+1] == 'V':
result = result + 3
jump = True
continue
elif s[index+1] == 'X':
result = result + 8
jump = True
continue
if char == 'X':
result = result + 10
if index < len(s)-1:
if s[index+1] == 'L':
result = result + 30
jump = True
continue
elif s[index+1] == 'C':
result = result + 80
jump = True
continue
if char == 'C':
result = result + 100
if index < len(s)-1:
if s[index+1] == 'D':
result = result + 300
jump = True
continue
elif s[index+1] == 'M':
result = result + 800
jump = True
continue
if char == 'V':
result = result + 5
if char == 'L':
result = result + 50
if char == 'D':
result = result + 500
if char == 'M':
result = result + 1000
return result
  • 想法:针对每个罗马数分情况讨论

Best Solution

Python

1
2
3
4
5
6
7
8
9
10
11
12
class :

# @return {integer}
def romanToInt(self, s):
roman = {'M': 1000,'D': 500 ,'C': 100,'L': 50,'X': 10,'V': 5,'I': 1}
z = 0
for i in range(0, len(s) - 1):
if roman[s[i]] < roman[s[i+1]]:
z -= roman[s[i]]
else:
z += roman[s[i]]
return z + roman[s[-1]]
  • 想法:把罗马数字对应的值储存在字典中,注意题目中的这句话:Roman numerals are usually written largest to smallest from left to right.