Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
O(n) time go through the whole string. O(1) space.
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
ROMAN_HASH = {
'M' : 1000,
'D' : 500,
'C' : 100,
'L' : 50,
'X' : 10,
'V' : 5,
'I' : 1
}
total_value = 0
previous_value = 0
for char in s:
current_value = ROMAN_HASH[char]
if previous_value < current_value:
total_value += current_value - 2 * previous_value
else:
total_value += current_value
previous_value = current_value
return total_value