DSA Factory
Free lessonsProgramming basics · Stage 9 · Mastery · Step 4

Roman numerals

Write a number the way the Romans did, by taking the biggest piece away again and again. About 14 minutes.

No label this time

Roman numerals write a number as pieces from a fixed menu: M is 1000, D is 500, C is 100, L is 50, X is 10, V is 5 and I is 1. 1994 is written MCMXCIV. To make it short, the Romans also had pairs where a small piece sits before a bigger one and is taken away: IV is 4, IX is 9, XL is 40, XC is 90, CD is 400 and CM is 900.

A small hint for this one. Put all thirteen pieces in order from biggest to smallest, in two lists that line up: the values and the symbols.

Before coding: what is the menu, and what order should I try it in?
Writing 1994
1000
0
900
1
500
2
400
3
100
4
90
5
50
6
40
7
10
8
9
9
5
10
4
11
1
12
value
n
994
result
M

Start with 1994. The biggest piece that fits is 1000, which is M. Take it away: 994 is left. The text so far is M.

Move 1 of 4
Quick check

How do the Romans write 4, using the menu of pieces?

  1. AIV
  2. BIIII
  3. CVI
Show the answer

IV. 4 has its own piece on the menu: I before V.

Your problem

Roman numeral

Return the Roman numeral for a number from 1 to 3999. Use these pieces: M 1000, CM 900, D 500, CD 400, C 100, XC 90, L 50, XL 40, X 10, IX 9, V 5, IV 4 and I 1.

Example
n = 1994 → "MCMXCIV"

1 ≤ n ≤ 3,999

Solve it in your browserPython, C++, Java or JavaScript. Hints if you get stuck. No sign-up needed.
Start coding