13. Roman to Integer
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000Input: "III"
Output: 3Last updated
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000Input: "III"
Output: 3Last updated
Input: "IV"
Output: 4Input: "IX"
Output: 9Input: "LVIII"
Output: 58
Explanation: C = 100, L = 50, XXX = 30 and III = 3.Input: "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
def switch(x):
return {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000,
}[x]
integer = 0
lastdigit = 0
for i in range(len(s)-1, -1, -1):
# If the last digit is larger, subtract
if switch(s[i]) < lastdigit:
integer -= switch(s[i])
else:
integer += switch(s[i])
lastdigit = switch(s[i])
return integer