Integer to Roman
Integer to Roman is LeetCode 12 (Medium). Given an integer num from 1 to 3999, return it written in Roman numerals.
- The seven symbols are
I1,V5,X10,L50,C100,D500 andM1000. - Symbols are written from largest to smallest and their values are added.
- Six values use subtraction instead:
IV4,IX9,XL40,XC90,CD400 andCM900. I,X,CandMcan repeat at most three times in a row;V,LandDnever repeat.
Because num stops at 3999, M is the largest symbol you ever need.
- 1 <= num <= 3999
Intuition
The six subtractive forms are the only awkward part, so treat them as symbols of their own. Add them to the seven real symbols and you get a table of 13 values: 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1.
Now walk that table from largest to smallest and take each value as many times as it still fits, subtracting it every time. Nothing checks for a 4 or a 9. When 94 is left, 90 is tried before 50, so XC is written and LXXXX never appears.
This is the same move as giving change with the biggest coin first, and here it always produces the one correct numeral.
Writing an amount using a fixed set of denominations, biggest first, is a greedy walk over a sorted table. Converting an integer to Roman numerals, giving change, and formatting a duration as hours, minutes and seconds all have that shape.
Approach
Before reading on, write 4, 9, 40, 90, 400 and 900 in Roman numerals and look at what they have in common. Then think of a way to produce them without writing an if for each one.
Two ways to solve it
Walk 13 values from largest to smallest and take each one while it fits.
- Short: one table and one loop.
- Explainable: the same idea as giving change.
The usual interview answer.
Split num into thousands, hundreds, tens and ones and look each digit up in a table of ready-made strings.
- No loop: four lookups and a join.
- More typing: 33 strings to get exactly right.
Handy if you think in place values.
Both run in constant time for this input range. The greedy table is shorter to write and easier to defend, so the steps, code and demo follow it; the digit lookup comes after the demo.
Build the value table
List the 13 value and symbol pairs from 1000 down to 1, with each subtractive pair sitting just above the symbol it replaces: 900 before 500, 4 before 5. The loop takes the first value that fits, so this order decides which form gets written.
Take each value while it fits
For each pair, while num is at least the value, append the symbol and subtract the value. A value can fit up to three times, which is how 3000 becomes MMM.
Move to the next smaller value
Once num drops below the value, step to the next pair. Every later pair is smaller, so a symbol is never needed again after you pass it, and the numeral comes out in largest-to-smallest order.
Join the pieces
After the last pair, num is 0, because the final value is 1 and it fits any positive remainder. Join the collected symbols into one string and return it.
Code in Python, C++ and Java
Lookup by decimal digit
Each decimal digit converts on its own, so precompute the Roman form of every digit for each place. num // 100 % 10 picks out the hundreds digit, and the matching string is read straight from the hundreds list. Index 0 holds an empty string, which is how a zero digit writes nothing.
Common pitfalls
Leaving the subtractive pairs out of the table
table = [(1000, "M"), (500, "D"), (100, "C"), (50, "L"),
(10, "X"), (5, "V"), (1, "I")]table = [(1000, "M"), (900, "CM"), (500, "D"), (400, "CD"), ...]
With only the seven symbols, 4 comes out as "IIII" and 9 as "VIIII". The values add up, but the answer is wrong, and patching it with if checks for each digit is where most bugs creep in.
Using if instead of while
if num >= value:
num -= value
result.append(symbol)while num >= value:
num -= value
result.append(symbol)An if takes each value at most once, so 3 returns "I" and 2000 returns "M". Any digit made of repeated symbols needs the loop.
Putting a subtractive pair after the symbol it replaces
table = [(1000, "M"), (500, "D"), (900, "CM"), ...]
table = [(1000, "M"), (900, "CM"), (500, "D"), ...]
For 900, D is tried first and fits, leaving 400, so the answer is "DCD". The table must be sorted strictly by value.
Edge cases
Roman numerals have no zero. Every value for that place is too big for what is left, so the loop writes nothing for it: 2005 is MMV.
It needs MMM plus three subtractive pairs: MMMCMXCIX. No symbol above M exists in the table, and none is needed below 4000.
Complexity
MMMDCCCLXXXVIII). The work never grows past that, whatever num is.Integer to Roman FAQ
Why is 999 not written as IM?
Subtraction only reaches one or two steps up: I goes before V or X, X before L or C, and C before D or M. So 999 is 900 + 90 + 9, which is CMXCIX. The table follows this rule for free, since it has no entry for 999.
Why does greedy work here when it fails for some coin change problems?
With coins 1, 3 and 4, greedy pays 6 as 4 + 1 + 1 instead of 3 + 3. Roman numerals avoid that trap because each decimal place is written on its own. Within a place the table holds 9, 5, 4 and 1 times that place, and taking the biggest that fits builds every digit exactly as the standard form does: 8 is 5 + 1 + 1 + 1, 9 is 9. A place never adds up to more than the next place's smallest value, so greedy never borrows across places.