13. Roman to Integer
# Easy
Solution:
if
roman{cur} < roman{next}
, two letters must be computed together,cur
andnext
pointers are moved 2 steps.if
roman{cur} >= roman{next}
, then only collect roman{cur}, cur and next pointers are moved 1 step.Don't forget to consider one last edge situation, if
cur
points to last element, add it tonum
directly, ifcur
points out of range, ignore it.
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
Was this helpful?