13. Roman to Integer
Last updated
Last updated
Input: "IV"
Output: 4Input: "IX"
Output: 9Input: "LVIII"
Output: 58
Explanation: L = 50, V= 5, 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
"""
romanDict = {'I':1,'IV':4,'V':5,'IX':9,'X':10,'XL':40,'L':50,
'XC':90,'C':100,'CD':400,'D':500,'CM':900,'M':1000}
res = 0
while len(s) > 0:
cur = s[0]
if cur == 'I' and len(s) != 1 and s[1] != 'I':
res += romanDict[s[1]] - romanDict[cur]
s = s[1:]
elif cur == 'X' and len(s) != 1 and romanDict[s[1]] > romanDict[cur]:
res += romanDict[s[1]] - romanDict[cur]
s = s[1:]
elif cur == 'C' and len(s) != 1 and romanDict[s[1]] > romanDict[cur]:
res += romanDict[s[1]] - romanDict[cur]
s = s[1:]
else:
res += romanDict[cur]
s = s[1:]
return res