Roman numerals are based on combining letters that represent certain values. The key symbols are: I = 1
, V = 5
, X = 10
, L = 50
, C = 100
, D = 500
, and M = 1000
.
To convert an integer into Roman numerals, we need to break it down from the highest possible value and work our way down. For example, for the number 58
:
- The highest Roman symbol less than 58 is
L = 50
- Next is
V = 5
- Then
III = 3
gives us the remaining 3 - So,
58
becomes LVIII
Some numbers need subtraction to avoid four repetitions of the same symbol. For instance:
4
is not IIII
, but IV
(5 - 1)
9
is IX
, 40
is XL
, 90
is XC
, and so on
So, to build the Roman numeral:
- We create a list of integer values and their matching Roman symbols, arranged from largest to smallest
- We loop through these values, and at each step, we subtract as many times as the value fits into the number
- For each subtraction, we append the corresponding Roman symbol to the result
This continues until the number becomes 0. For example:
1994
is broken into: M (1000) + CM (900) + XC (90) + IV (4)
→ MCMXCIV
What if the input is invalid?
If the input is 0, negative, or not a number (like an empty string or null), it cannot be converted to a Roman numeral because Roman numerals only support positive integers from 1 to 3999. In such cases, return a clear message like "Invalid input"
.
This approach is simple, efficient, and gives the correct result for any input within the valid range.