VOOZH about

URL: https://www.geeksforgeeks.org/dsa/converting-decimal-number-lying-between-1-to-3999-to-roman-numerals/

⇱ Converting Decimal Number lying between 1 to 3999 to Roman Numerals - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Converting Decimal Number lying between 1 to 3999 to Roman Numerals

Last Updated : 30 Apr, 2025

Given an integer, convert it into its equivalent Roman numeral representation.

Note: Following is the list of Roman symbols (including subtractive cases):

SymbolValue
I1
IV4
V5
IX9
X10
XL40
L50
XC90
C100
CD400
D500
CM900
M1000

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 = 10
  • IX means 10 - 1 = 9

Input: 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 = 50
  • XL means 50 - 10 = 40

[General Purpose Solution] - O(n) Time and O(n) Space

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

  • Since 3549 >= 1000 ; largest base value will be 1000 initially.
  • Divide 3549/1000. Quotient = 3, res = "MMM" (Note M belongs to 1000)
  • Remainder = 549

Iteration 2

  • 1000 > 549 >= 500 ; largest base value will be 500.
  • Divide 549/500. Quotient = 1, .res = "MMMD"
  • Remainder = 49

Iteration 3

  • 50 > 49 >= 40 ; largest base value is 40.
  • Divide 49/40. Quotient = 1, res = "MMMDXL"
  • Remainder = 9.

Iteration 4

  • Number 9 is present in list. res = "MMMDXL"
  • Remainder = 0.

Output
MMMDXLIX

Time Complexity: O(n), where n is the length of the answer string that stores the conversion.
Auxiliary Space: O(n)

[For Limited Range] - O(n) Time and O(n) Space

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.


Output
MMMDXLIX
Comment
Article Tags: