Roman to Integer
Read a Roman numeral such as MCMXCIV and return the number it stands for.
Given a string s
Example 1
Output: 3
Example 2
Output: 58
Explanation: L = 50, V = 5, III = 3.
Example 3
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90, IV = 4.
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 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, valueswitchHashMapswitch
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
- First, start a running sum,
, at 0.total - A loop moves the index
over the string from left to right. At each position,i gets the value of the symbolv from the helpers.charAt(i) .value - If there is a symbol after it (
) andi + 1 < s.length() is smaller than that symbol's value, subtractv fromv . Otherwise, addtotal . Thev checks the position first, so for the last symbol the next character is never read.&& - After the loop,
is the number, and the method returns it.total
The main
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:
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 -> 1XLIX -> 49
The "strictly smaller" test matters. With <=<
The original implementation,
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 andi are kept, and the symbol values come from thev , not from a stored table.switch
The opposite direction, from a number to a Roman numeral, is