lookahead comparison
For each symbol, peek at the next one. If the current value is strictly less than the next value, the current symbol is subtractive. Otherwise, it adds normally.
Ancient Roman inscriptions carved dates and quantities using seven symbols — I, V, X,
L, C, D, M — with a subtractive twist: a smaller symbol placed before a larger one
means "subtract me." Converting a Roman string to an integer requires nothing more than
a left-to-right scan with a one-symbol lookahead: if the current value is less than the
next, subtract it; otherwise, add it. O(n) time. O(1) space.
Each Roman symbol is either additive or subtractive. The decision depends entirely on whether the next symbol represents a larger value.
For each symbol, peek at the next one. If the current value is strictly less than the next value, the current symbol is subtractive. Otherwise, it adds normally.
Only six combinations trigger subtraction: IV (4), IX (9), XL (40), XC (90), CD (400), CM (900). All follow the same lookahead rule — no special-casing needed.
The final symbol has no successor to compare against. Without a larger value on its right, it can never participate in a subtractive pair — so it always contributes positively.
A single pass resolves every symbol. No backtracking, no grouping, no pattern matching.
The running total starts at 0. Each symbol will either increase or decrease it.
Map the current character to its integer value. If a next character exists, map it too; otherwise treat the next value as 0.
If current < next, subtract the current value from the total. Otherwise, add it. This single comparison handles all six subtractive pairs.
After processing every symbol left to right, the total holds the integer equivalent of the Roman numeral.
Some inputs have no subtractive pairs at all, while others are composed entirely of them.
A one-character string like V has no next symbol. The lookahead
comparison never triggers subtraction — the symbol's value is the answer.
Strings like III or XXX have every symbol equal to its
successor. Equal values never trigger subtraction — every symbol adds.
A numeral like CMXCIX (999) is composed entirely of subtractive pairs.
Every odd-indexed symbol is larger than the one before it, creating an alternating
subtract-add pattern throughout.