Integer to Roman numeral
Medium TimeO(1) SpaceO(1)
Every number from 1 to 3999 has one standard Roman numeral: the one written with the fewest symbols, which is why 900 is "CM" and not "DCCCC". Given num, return that numeral. No symbol appears more than three times in a row, and the six subtractive pairs CM, CD, XC, XL, IX and IV are used wherever they fit.
Examples
Example 1
- Input
- num = 1994
- Output
"MCMXCIV"1000 + 900 + 90 + 4, one symbol group each:M,CM,XC,IV.
Example 2
- Input
- num = 3000
- Output
"MMM"1000 + 1000 + 1000, the same symbol three times.
The Code
function intToRoman(num) {
const values = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
const symbols = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"];
let out = "";
for (let i = 0; i < values.length; i++) {
while (num >= values[i]) {
out += symbols[i];
num -= values[i];
}
}
return out;
}
intToRoman(1994);Done
The first 17 calls, of 23. This one does not fit on a page.
More like this
All math & numbers examples (8) →- Prime check Only test odd divisors, and only up to the square root.
- Prime sieve Cross out every multiple; whatever survives is prime.
- Happy number Sum the squared digits until you reach 1 — or start repeating.
- Roman → integer Subtract when a smaller symbol sits before a bigger one.
- Collatz Halve it if even, triple-plus-one if odd — always reaches 1.
- Newton’s sqrt Average your guess with n over your guess; it converges fast.