Tutorialspoint
Problem
Solution
Submissions

Convert a Roman Numeral to an Integer

Certification: Basic Level Accuracy: 50% Submissions: 46 Points: 10

Write a Python program that converts a Roman numeral to an integer. Roman numerals are represented by combinations of letters from the Latin alphabet (I, V, X, L, C, D, M). Roman numerals are usually written largest to smallest from left to right. However, when a smaller value precedes a larger value, the smaller value is subtracted from the larger value.

Example 1
  • Input: roman = "III"
  • Output: 3
  • Explanation:
    • Step 1: Create a mapping of Roman symbols to their integer values (I=1, V=5, X=10, etc.).
    • Step 2: Iterate through the Roman numeral string from left to right.
    • Step 3: For "III", we add 1 + 1 + 1 = 3.
    • Step 4: Return the resulting integer value.
Example 2
  • Input: roman = "MCMXCIV"
  • Output: 1994
  • Explanation:
    • Step 1: Create a mapping of Roman symbols to their integer values.
    • Step 2: Iterate through the Roman numeral string from left to right.
    • Step 3: M = 1000
    • Step 4: C before M represents 900 (1000-100)
    • Step 5: X before C represents 90 (100-10)
    • Step 6: I before V represents 4 (5-1)
    • Step 7: Adding all values: 1000 + 900 + 90 + 4 = 1994
    • Step 8: Return the resulting integer value.
Constraints
  • 1 ≤ len(roman) ≤ 15
  • Roman numeral is valid and in the range [1, 3999]
  • Time Complexity: O(n) where n is the length of the roman numeral string
  • Space Complexity: O(1)
StringsMapCapgeminiSnowflake
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 a dictionary mapping Roman symbols to their values
  • Iterate through the string and compare adjacent symbols
  • If current value is less than next value, subtract the current value
  • If current value is greater than or equal to next value, add the current value
  • Add the last symbol's value at the end of iteration
  • Special cases: IV = 4, IX = 9, XL = 40, XC = 90, CD = 400, CM = 900

Steps to solve by this approach:

 Step 1: Create a dictionary mapping Roman numerals to their integer values.

 Step 2: Initialize a result variable to store the final integer value.
 Step 3: Iterate through the Roman numeral string.
 Step 4: Compare each symbol with the next symbol to determine whether to add or subtract.
 Step 5: If current symbol value is less than next symbol value, subtract it from result.
 Step 6: Otherwise, add the current symbol value to the result.
 Step 7: Return the final integer result.

Submitted Code :