Roman numerals
A JavaScript exercise from Scriptdrill. Solve it with a code editor in your browser that runs your function against example and hidden tests, and it is checked the moment you submit.
The task
Convert an integer `n` from 1 to 3999 to a Roman numeral string. The symbols are I (1), V (5), X (10), L (50), C (100), D (500) and M (1000). Use the subtractive forms: 4 is `IV`, 9 is `IX`, 40 is `XL`, 90 is `XC`, 400 is `CD` and 900 is `CM`, so 1994 is `MCMXCIV`.
What this exercise teaches
A greedy walk over a table that includes the subtractive pairs (900, 400, 90, 40, 9, 4) produces the standard form in one pass. Leaving those pairs out gives VIIII instead of IX, which only shows for numbers that contain a 4 or a 9 at some position.
A hint if you get stuck
Keep a table of values and symbols from largest to smallest, including the six subtractive pairs. Walk the table and, while `n` is at least the value, append the symbol and subtract.
Try it now, free, no account needed
Every exercise on Scriptdrill is free to try. Open it on the practice page, solve it, and get instant feedback with a hint. The worked solution opens once you solve it or after two tries.
Open this exerciseMore exercises in Basics
- Total of a listFree
- Items in stockFree
- Full namesFree
- Has every tagFree
- Reverse the wordsFree
- Capitalize each wordFree
- Count the vowelsFree
- Clamp a numberFree
- Range of numbersFree
- FizzBuzzFree
- Palindrome checkFree
- Anagram checkFree
- Fibonacci numbersFree
- Balanced bracketsFree