Integer to Roman

Medium#12biggest piece first

Write a whole number from 1 to 3999 in Roman numerals. I, V, X, L, C, D and M are 1, 5, 10, 50, 100, 500 and 1000, written from the biggest down and added up. A symbol may repeat at most three times; for 4, 9, 40, 90, 400 and 900 a smaller symbol goes before a bigger one and is taken away: IV, IX, XL, XC, CD, CM. Our example: 2894 — the answer is "MMDCCCXCIV".

input
num: a positive integer.
returns
num in Roman numerals: I 1, V 5, X 10, L 50, C 100, D 500, M 1000, written from the largest value down. Instead of four symbols in a row, 4, 9, 40, 90, 400 and 900 are written as a smaller symbol before a larger one: IV, IX, XL, XC, CD, CM.
constraints
  • 1 ≤ num ≤ 3999
our 16 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number} num
 * @return {string}
 */
function intToRoman(num) {

}
Ctrl ↵
format
reset

saved in this browser

16 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more greedy problems

Pattern “Greedy” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.