
[LeetCode] 13. Roman to Integer


class Solution:
def romanToInt(self, s: str) -> int:
roman_to_int = {
"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000
}
total = 0
n = len(s)
for i in range(n - 1):
# if current < next, subtract
if roman_to_int[s[i]] < roman_to_int[s[i + 1]]:
total -= roman_to_int[s[i]]
# else, add
else:
total += roman_to_int[s[i]]
# always add last char
total += roman_to_int[s[-1]]
return total