Roman to Integer

Read a Roman numeral such as MCMXCIV and return the number it stands for.

Given a string s that holds a Roman numeral, return the number it stands for. The symbols are I = 1, V = 5, X = 10, L = 50, C = 100, D = 500 and M = 1000. Symbols are normally written from largest to smallest and added up. Six pairs are the exception: IV, IX, XL, XC, CD and CM mean 4, 9, 40, 90, 400 and 900. The input is always a valid numeral from 1 to 3999.

Example 1
Input: s = "III"
Output: 3
Example 2
Input: s = "LVIII"
Output: 58
Explanation: L = 50, V = 5, III = 3.
Example 3
Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90, IV = 4.
Solution

The Idea

You have probably seen Roman numerals on clock faces, as chapter numbers in old books, or as the year at the end of a film. Reading one is mostly adding. In "LVIII", each symbol is at least as large as the one after it, so the value is 50 + 5 + 1 + 1 + 1 = 58.

Then comes "IV". Adding gives 1 + 5 = 6, but IV means 4: the I is taken away from the V. The same happens in the six pairs from the problem statement. So how can a program tell when to take a symbol away, without a list of the six pairs?

Look at what the six pairs have in common. In each of them, the first symbol is smaller than the second: I before V, X before C, C before M. Everywhere else, a symbol is followed by one that is the same size or smaller. That gives one rule for every symbol: if it is smaller than the symbol right after it, subtract it; otherwise, add it.

Look at the picture below, which applies the rule to "MCMXCIV".

The symbols of MCMXCIV with their values. C before M, X before C and I before V are smaller than the symbol after them, so they count as minus 100, minus 10 and minus 1. The others are added, and the total is 1994.

The row labelled "symbol" shows the seven symbols, and the row labelled "value" shows what each is worth on its own. The orange arrows join each symbol to a larger one right after it: C to M, X to C and I to V. Those three count as −100, −10 and −1 in the row labelled "counts as", and every other symbol counts as plus its value.

The last row adds them up: 1000 − 100 + 1000 − 10 + 100 − 1 + 5 = 1994. Read in pairs, −100 + 1000 is the 900 of CM, −10 + 100 is the 90 of XC, and −1 + 5 is the 4 of IV. So the pairs never need to be found as pairs. Each symbol only has to look at its right-hand neighbour.

Solution Approach

Turning that rule into code means settling three things: how to find each symbol's value, how to choose between adding and subtracting, and what to do with the last symbol.

The value of each symbol

How does the program know that C is worth 100? A small helper method, value, takes one character and returns its number with a switch, one case per symbol. Since the input only holds valid symbols, M can be the default case. A HashMap from character to number would work as well, but seven fixed symbols fit a switch with nothing to build first.

Adding or subtracting

Which test decides the sign? One way is to look ahead for each of the six pairs by name, which means six checks for every position. Comparing the symbol's value with the next symbol's value covers all six at once.

The comparison must be "strictly smaller". In "III", every I is followed by an I of the same size, and all three must be added. Only a symbol that is smaller than its neighbour is subtracted.

The last symbol

What about the last symbol, which has no neighbour on its right? Nothing can follow it, so it is always added. The code checks that a next position exists before it reads the next character, so it never reads past the end of the string.

Java Solution

The method romanToInt works in these steps:

  1. First, start a running sum, total, at 0.
  2. A loop moves the index i over the string from left to right. At each position, v gets the value of the symbol s.charAt(i) from the helper value.
  3. If there is a symbol after it (i + 1 < s.length()) and v is smaller than that symbol's value, subtract v from total. Otherwise, add v. The && checks the position first, so for the last symbol the next character is never read.
  4. After the loop, total is the number, and the method returns it.

The main method runs the three examples, a single symbol, "XLIX" with two subtracted symbols, and "MMMCMXCIX", the largest valid input.

Java
public class RomanToInteger {

    public static int romanToInt(String s) {
        int total = 0;
        for (int i = 0; i < s.length(); i++) {
            int v = value(s.charAt(i));
            if (i + 1 < s.length() && v < value(s.charAt(i + 1))) {
                total -= v;                   // smaller than the next symbol: IV, XC, ...
            } else {
                total += v;
            }
        }
        return total;
    }

    private static int value(char c) {
        switch (c) {
            case 'I': return 1;
            case 'V': return 5;
            case 'X': return 10;
            case 'L': return 50;
            case 'C': return 100;
            case 'D': return 500;
            default:  return 1000;            // 'M'
        }
    }

    public static void main(String[] args) {
        String[] tests = {"III", "LVIII", "MCMXCIV", "I", "XLIX", "MMMCMXCIX"};
        for (String s : tests) {
            System.out.println(s + " -> " + romanToInt(s));
        }
    }
}

Running it prints:

Output
III -> 3
LVIII -> 58
MCMXCIV -> 1994
I -> 1
XLIX -> 49
MMMCMXCIX -> 3999

III, LVIII and MCMXCIV come out as 3, 58 and 1994, the values from the examples. In I -> 1, the only symbol is also the last one, so the position check stops the comparison and the I is added. XLIX -> 49 has two subtracted symbols: −10 + 50 − 1 + 10 = 49. The last line reaches 3999, the top of the allowed range.

The "strictly smaller" test matters. With <= in place of <, equal neighbours are subtracted too. That version returns -1 for "III" (−1 − 1 + 1) and 54 for "LVIII". It still returns 1994 for "MCMXCIV", because no two neighbours there are equal, so that example alone would not reveal the bug.

The original implementation, RomanToInteger.java, is on GitHub.

Complexity

The method makes one pass over the numeral and keeps only a running sum.

  • Time: O(n), because the loop visits each of the n symbols once and looks up at most two values there, its own and its neighbour's. A valid numeral up to 3999 has at most 15 symbols (MMMDCCCLXXXVIII, 3888), so the work is always small.
  • Space: O(1), because only total, i and v are kept, and the symbol values come from the switch, not from a stored table.

The opposite direction, from a number to a Roman numeral, is Integer to Roman.