13. Roman to Integer
# Easy
Solution:
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
roman = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C':100, 'D': 500, 'M': 1000}
# edge case
if len(s) == 1:
return roman[s[0]]
# regular case
cur = 0
nex = 1
num = 0
while nex < len(s):
if roman[s[cur]] < roman[s[nex]]: # bind two letters (such as 90, 'XC')
num += roman[s[nex]] - roman[s[cur]]
cur += 2
nex += 2
else: # only one single letter (such as 100~'C', 80~'LXXX')
num += roman[s[cur]]
cur += 1
nex += 1
if cur == len(s) - 1:
num += roman[s[cur]]
return num
Last updated