Roman Numerals
Medium · 55 XPWrite to_roman(n) converting an integer (1–3999) to a Roman numeral. Print the result for 4, 44, 1994 and 3999.
IV XLIV MCMXCIV MMMCMXCIX
Walk a value→symbol table from largest to smallest, including the subtractive pairs (900 CM, 400 CD, 90 XC, 40 XL, 9 IX, 4 IV).
def to_roman(n):
table = [(1000, "M"), (900, "CM"), (500, "D"), (400, "CD"),
(100, "C"), (90, "XC"), (50, "L"), (40, "XL"),
(10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I")]
out = ""
for value, symbol in table:
while n >= value:
out += symbol
n -= value
return out
for n in (4, 44, 1994, 3999):
print(to_roman(n))
Run your code to check it…
How to approach Roman Numerals
Roman numerals are built greedily: take the biggest symbol that still fits, subtract its value, and repeat. The only subtlety is the subtractive forms such as IV for 4 and CM for 900.
The clean way to handle them is to stop treating them as exceptions. Put the six subtractive pairs in the value table alongside the seven ordinary symbols, sorted from 1000 down to 1, and the same greedy loop produces correct numerals for every number from 1 to 3999.
Worked through on this data
- 1994: M fits (1000), leaving 994. CM fits (900), leaving 94.
- XC fits (90), leaving 4. IV fits (4), leaving 0.
- Joined: MCMXCIV. The same process gives IV for 4, XLIV for 44 and MMMCMXCIX for 3999.
Common mistakes
- Leaving out the subtractive pairs gives IIII for 4 and DCCCC for 900.
- Putting the table in the wrong order (for example 500 before 900) lets D grab 1994 first and produces nonsense.
- Using
ifinstead ofwhilefor each symbol writes 3 as I instead of III.
Time and space
The table has 13 entries and no numeral up to 3999 is longer than 15 symbols, so the work is bounded: O(1) for this input range.
Where this shows up
Greedy selection from a sorted table is how change-making in tills works, and how human-readable durations such as "2h 15m" and file sizes such as "3.4 MB" are formatted.
Take it further
Write from_roman(s): add each symbol's value, but subtract it when a larger symbol follows it. Check that every number from 1 to 3999 round-trips.