Problems › JavaScript › warmup
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.
toRoman(amount: int) → string
Where you start
function toRoman(amount) {
}
Worked examples
| Call | Result |
|---|---|
toRoman(1) | "I" |
toRoman(4) | "IV" |
toRoman(14) | "XIV" |
toRoman(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 JavaScript
function toRoman(amount) {
if (amount < 1 || amount > 3999) return '';
const vals = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
const syms = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'];
let n = amount, result = '';
for (let i = 0; i < vals.length; i++) {
while (n >= vals[i]) { result += syms[i]; n -= vals[i]; }
}
return result;
}