forked from algorhythms/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path013 Roman to Integer.py
More file actions
38 lines (29 loc) · 838 Bytes
/
013 Roman to Integer.py
File metadata and controls
38 lines (29 loc) · 838 Bytes
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
"""
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
"""
__author__ = 'Danyang'
roman2int = {
"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000
}
class Solution:
def romanToInt(self, s):
"""
What happens if current roman char larger than the previous roman char?
:param s: String
:return: integer
"""
result = 0
for ind, val in enumerate(s):
if ind > 0 and roman2int[val] > roman2int[s[ind-1]]: # e.g. XIV
result -= roman2int[s[ind-1]] # reverse last action
result += roman2int[val]-roman2int[s[ind-1]]
else:
result += roman2int[val]
return result