Tutorialspoint
Problem
Solution
Submissions

Convert an Integer to a Roman Numeral

Certification: Basic Level Accuracy: 85.29% Submissions: 34 Points: 10

Write a Python program that converts an integer to a Roman numeral. Roman numerals are represented by combinations of letters from the Latin alphabet (I, V, X, L, C, D, M). The program should handle integers from 1 to 3999.

Example 1
  • Input: num = 58
  • Output: "LVIII"
  • Explanation:
    • Step 1: Create a mapping of integer values to Roman symbols.
    • Step 2: 50 is represented as 'L'.
    • Step 3: 8 is represented as 'VIII' (5 + 3).
    • Step 4: Combine them to get "LVIII".
    • Step 5: Return the resulting Roman numeral.
Example 2
  • Input: num = 1994
  • Output: "MCMXCIV"
  • Explanation:
    • Step 1: Create a mapping of integer values to Roman symbols, including subtractive combinations.
    • Step 2: 1000 is represented as 'M'.
    • Step 3: 900 is represented as 'CM' (1000-100).
    • Step 4: 90 is represented as 'XC' (100-10).
    • Step 5: 4 is represented as 'IV' (5-1).
    • Step 6: Combine them to get "MCMXCIV".
    • Step 7: Return the resulting Roman numeral.
Constraints
  • 1 ≤ num ≤ 3999
  • Time Complexity: O(1) since there is a finite set of Roman numeral symbols
  • Space Complexity: O(1)
StringsNumberListEYAdobe
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Create two lists: one for values and one for corresponding Roman symbols
  • Start from the largest value and work down to the smallest
  • Use integer division and modulo to find the number of times each symbol is used
  • Append the appropriate number of symbols to the result string
  • Handle special cases: 4, 9, 40, 90, 400, 900 with their own symbols
  • Use a greedy approach to choose the largest possible symbol at each step

Steps to solve by this approach:

 Step 1: Define ordered lists of integer values and their corresponding Roman numerals.

 Step 2: Initialize an empty string to store the Roman numeral result.
 Step 3: Iterate through the values list and their corresponding numerals.
 Step 4: Calculate how many times each value fits into the remaining number using integer division.
 Step 5: Append the corresponding numeral that many times to the result string.
 Step 6: Update the number by taking the remainder after division.
 Step 7: Return the completed Roman numeral string.

Submitted Code :