Write a number in Roman numerals
A film credit or a chapter heading wants MCMXCIV rather than 1994.
- The subtractive forms count: 4 is IV, 9 is IX, 40 is XL, 90 is XC, 400 is CD, 900 is CM.
- Only 1 to 3999 can be written; anything outside gives an empty string.
to_roman(amount: int) → string
Where you start
def to_roman(amount: int) -> str:
Worked examples
| Call | Result |
|---|---|
to_roman(1) | "I" |
to_roman(4) | "IV" |
to_roman(14) | "XIV" |
to_roman(1994) | "MCMXCIV" |
Hint
Keep the values and their symbols in one descending table, including the subtractive pairs. Then it is one greedy pass.
Reference solution in Python
def to_roman(amount: int) -> str:
if amount < 1 or amount > 3999:
return ''
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')]
n = amount
result = ''
for v, sym in table:
while n >= v:
result += sym
n -= v
return result