![]() |
VOOZH | about |
Given an integer, convert it into its equivalent Roman numeral representation.
Note: Following is the list of Roman symbols (including subtractive cases):
| Symbol | Value |
|---|---|
| I | 1 |
| IV | 4 |
| V | 5 |
| IX | 9 |
| X | 10 |
| XL | 40 |
| L | 50 |
| XC | 90 |
| C | 100 |
| CD | 400 |
| D | 500 |
| CM | 900 |
| M | 1000 |
Examples:
Input: 9
Output: IX
Explanation: 9 is written as "IX" in Roman numerals using subtractive notation — placing a smaller numeral before a larger one.
I= 1,X= 10IXmeans 10 - 1 = 9Input: 40
Output: XL
Explanation: 40 is written as "XL" in Roman numerals using subtractive notation — placing a smaller numeral before a larger one.
X= 10, L = 50XLmeans 50 - 10 = 40
Compare given number with base values in the order 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1. Once we find the largest base value that is less than the given number, we divide the number with the base value and repeat the process for smaller base values and quotient. We add the roman symbol corresponding to the base value found to the result, number of times equal to the quotient and repeat the process for remainder.
Let us understand the approach with an example 3549
Iteration 1
Iteration 2
Iteration 3
Iteration 4
MMMDXLIX
Time Complexity: O(n), where n is the length of the answer string that stores the conversion.
Auxiliary Space: O(n)
The idea is based on the fact that we have a limited range to covert 0 to 3999. We isolate the digits corresponding to the thousands, hundreds, tens, and ones places, and then mapping each digit to its respective Roman numeral equivalent based on its positional value.
- Store mappings of character M for different quotients, 0, 1, 2, 3
- Store mappings of C, L and I for different quotients form 0 to 9.
Using the above mappings, we directly generate the result string.
MMMDXLIX