Add, unless a smaller digit precedes a larger one
Scan left to right. If cur < next, subtract cur (the IV / IX / XL … rule). Otherwise add it.
Standard Roman is additive. The six subtractive pairs are exactly “a smaller value sitting before a larger one.”
Algorithm
- Map each letter to its value.
- For each digit, add it, or subtract it when the next one is larger.
- Time
- O(n)
- Space
- O(1)
class Solution: def romanToInt(self, s: str) -> int: val = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} total = 0 for i, ch in enumerate(s): cur = val[ch] nxt = val[s[i + 1]] if i + 1 < len(s) else 0 total += -cur if cur < nxt else cur return total