Roman to Integer · Optimal Solution

Peek ahead. Add or subtract.

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.


Interactive

Watch the total accumulate


Concept

One rule decides every symbol

Each Roman symbol is either additive or subtractive. The decision depends entirely on whether the next symbol represents a larger value.

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.

six subtractive pairs

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.

last symbol always adds

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.


Algorithm

Scan, compare, accumulate

A single pass resolves every symbol. No backtracking, no grouping, no pattern matching.

  1. 1

    Initialize total to zero

    The running total starts at 0. Each symbol will either increase or decrease it.

  2. 2

    For each symbol, get current and next values

    Map the current character to its integer value. If a next character exists, map it too; otherwise treat the next value as 0.

  3. 3

    Compare: subtract or add

    If current < next, subtract the current value from the total. Otherwise, add it. This single comparison handles all six subtractive pairs.

  4. 4

    Return the total

    After processing every symbol left to right, the total holds the integer equivalent of the Roman numeral.


Edge Cases

Where subtraction never fires

Some inputs have no subtractive pairs at all, while others are composed entirely of them.

Single symbol

A one-character string like V has no next symbol. The lookahead comparison never triggers subtraction — the symbol's value is the answer.

All identical symbols

Strings like III or XXX have every symbol equal to its successor. Equal values never trigger subtraction — every symbol adds.

All subtractive pairs

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.