Integer to Roman

Write a number from 1 to 3999 as a Roman numeral, taking the largest symbol that fits at each step.

Given an integer num from 1 to 3999, return it written as a Roman numeral. Roman numerals use seven symbols: I = 1, V = 5, X = 10, L = 50, C = 100, D = 500 and M = 1000. Symbols are written from largest to smallest and their values are added, so 58 is L, V and three Is: LVIII.

A 4 or a 9 in any decimal place is written by putting a smaller symbol before a larger one, which subtracts it: IV (4), IX (9), XL (40), XC (90), CD (400) and CM (900). I, X, C and M may repeat up to three times in a row.

Example 1
Input: num = 3749
Output: "MMMDCCXLIX"
Explanation: 3000 = MMM, 700 = DCC, 40 = XL, 9 = IX.
Example 2
Input: num = 58
Output: "LVIII"
Explanation: 50 = L, 8 = VIII.
Example 3
Input: num = 1994
Output: "MCMXCIV"
Explanation: 1000 = M, 900 = CM, 90 = XC, 4 = IV.
Solution

The Idea

You have probably seen Roman numerals on clock faces, in chapter numbers, or at the end of film credits, where MCMXCIV stands for the year 1994. Each letter has a value, and the values are added from left to right: LVIII is 50 + 5 + 1 + 1 + 1 = 58.

Going the other way, from a number to letters, looks just as easy: keep writing the biggest symbol that still fits. For 58, L (50) fits and leaves 8, V (5) leaves 3, and three Is finish it. Now try 1994. M takes 1000 and leaves 994. The biggest of the seven symbols that fits 994 is D, and then four Cs take the next 400, giving MDCCCC. That breaks the rule of at most three Cs in a row, and Example 3 starts with MCM instead.

The hundreds digit of 1994 is a 9, and 900 is written CM: a C before an M, which means 1000 minus 100. So the seven plain symbols are not enough. What if the six subtractive forms, CM, CD, XC, XL, IX and IV, count as symbols of their own, worth 900, 400, 90, 40, 9 and 4? Then there are 13 symbols, from M = 1000 down to I = 1. Look at the picture below.

Converting 1994: take M = 1000, leaving 994; take CM = 900, leaving 94; take XC = 90, leaving 4; take IV = 4. Written so far grows M, MCM, MCMXC, MCMXCIV. At 994, D = 500 also fits, but CM = 900 is larger.

Each row starts from the number in the column "left to write" and takes the largest of the 13 symbols that fits it. In the second row, in orange, 994 is left: D = 500 fits, but CM = 900 is larger, so CM is written. Then XC takes 90 of the 94, and IV takes the last 4. The column "written so far" ends with MCMXCIV, the answer to Example 3.

So with the subtractive forms in the list, "take the biggest symbol that fits" works after all. Taking the biggest piece that fits at each step, without ever looking ahead or going back, is called a greedy method.

Solution Approach

Turning that idea into code means settling three things: what the table of symbols holds, how to walk through it, and why the greedy choice never writes a wrong numeral.

The table of 13 symbols

What does the table hold? Each of the 13 symbols with its value, sorted from largest to smallest: 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4 and 1. Two arrays side by side hold them, one for the values and one for the symbols, so position i of one belongs with position i of the other.

The simple way would be a table with only the seven plain symbols. Then 4 comes out as IIII and 1994 as MDCCCCLXXXXIIII, which add up correctly but break the rule of at most three repeats.

Walking through the table

How often can one symbol be written? Up to three times, as in MMM for 3000. So for each symbol, the code keeps writing it and subtracting its value while the number left is at least that value. Only then does it move on to the next, smaller symbol. It never needs to come back to a larger symbol, because what is left is now smaller than the one it just finished with.

Why the greedy choice is always right

Could the largest symbol ever lead the wrong way? Roman numerals write each decimal place on its own: thousands, then hundreds, then tens, then ones. The hundreds symbols CM, D, CD and C are worth 100 or more, and every symbol after them is worth 90 or less. So the walk writes the whole hundreds digit before it reaches the tens.

Within one place, the greedy choice gives the right letters. A hundreds digit of 9 takes CM, a digit from 5 to 8 takes D and then up to three Cs, a 4 takes CD, and 1 to 3 take that many Cs. The tens work the same way with XC, L, XL and X, and the ones with IX, V, IV and I.

Java Solution

The method intToRoman works in these steps:

  1. First, two arrays hold the table: VALUES has the 13 values, largest first, and SYMBOLS has the matching symbols at the same positions.
  2. Create a StringBuilder, sb, to collect the symbols. It appends to one growing buffer instead of making a new String for every symbol.
  3. A for loop moves an index i over the 13 positions, from 1000 down to 1.
  4. Inside, a while loop appends SYMBOLS[i] to sb and subtracts VALUES[i] from num, for as long as num is at least VALUES[i].
  5. After the last position, I, num is 0, so return sb.toString().

The main method converts the three examples, the smallest input 1, the single subtractive forms 4 and 9, the largest input 3999, and 3888, printing each numeral with its length.

Java
public class IntegerToRoman {

    private static final int[] VALUES = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
    private static final String[] SYMBOLS =
            {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};

    public static String intToRoman(int num) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < VALUES.length; i++) {
            while (num >= VALUES[i]) {        // take the largest symbol that still fits
                sb.append(SYMBOLS[i]);
                num -= VALUES[i];
            }
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        int[] tests = {3749, 58, 1994, 1, 4, 9, 3999, 3888};
        for (int num : tests) {
            String roman = intToRoman(num);
            System.out.println(num + " -> " + roman + ", length " + roman.length());
        }
    }
}

Running it prints:

Output
3749 -> MMMDCCXLIX, length 10
58 -> LVIII, length 5
1994 -> MCMXCIV, length 7
1 -> I, length 1
4 -> IV, length 2
9 -> IX, length 2
3999 -> MMMCMXCIX, length 9
3888 -> MMMDCCCLXXXVIII, length 15

3749 becomes MMMDCCXLIX, with M written three times by the while loop, and 1994 becomes MCMXCIV, the same letters as the last row of the picture. The lines for 4 and 9 show IV and IX, each taken as one table entry rather than built from I and V.

Look at the last two lines. 3999 is the largest input, yet its numeral, MMMCMXCIX, has only 9 characters, because each 9 is a two-letter pair. 3888 needs 15: MMM, then four letters for each 8, as in DCCC. Converting every number from 1 to 3999 the same way, no numeral is longer than 3888's.

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

Complexity

The work is one walk over the 13 table entries, plus one append for each symbol written.

  • Time: O(1), because the input is at most 3999. The for loop visits 13 entries, and the while loop appends at most 15 symbols in total, the length of 3888's numeral.
  • Space: O(1). The two tables have a fixed 13 entries each, and sb never holds more than 15 characters.

The reverse conversion, from letters back to a number, is Roman to Integer.