Tutorialspoint
Problem
Solution
Submissions

Roman to Integer

Certification: Basic Level Accuracy: 0% Submissions: 0 Points: 5

Write a C program to convert a Roman numeral to an integer. Roman numerals are represented by combinations of letters from the Latin alphabet. Roman numerals are I, V, X, L, C, D, and M which represent the values 1, 5, 10, 50, 100, 500, and 1000 respectively. Roman numerals are usually written largest to smallest from left to right. However, in some cases, a smaller numeral appears before a larger numeral, and in this case, the smaller value is subtracted from the larger value.

Example 1
  • Input: s = "LVIII"
  • Output: 58
  • Explanation:
    • We break down "LVIII" as "L" + "V" + "III".
    • L = 50, V = 5, I = 1, I = 1, I = 1.
    • 50 + 5 + 1 + 1 + 1 = 58. Therefore, the Roman numeral "LVIII" represents the integer 58.
Example 2
  • Input: s = "MCMXCIV"
  • Output: 1994
  • Explanation:
    • We break down "MCMXCIV" as "M" + "CM" + "XC" + "IV".
    • M = 1000, CM = 900 (1000-100), XC = 90 (100-10), IV = 4 (5-1).
    • 1000 + 900 + 90 + 4 = 1994.
    • Therefore, the Roman numeral "MCMXCIV" represents the integer 1994.
Constraints
  • The input string represents a valid Roman numeral in the range [1, 3999]
  • The string length will be between 1 and 15
  • The string will only contain the characters 'I', 'V', 'X', 'L', 'C', 'D', 'M'
  • Time Complexity: O(n), where n is the length of the input string
  • Space Complexity: O(1)
NumberFacebookKPMG
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 mapping for each Roman numeral character to its integer value
  • Iterate through the input string from left to right
  • For each character, compare its value with the value of the next character
  • If the current value is less than the next value, subtract it from the result
  • Otherwise, add it to the result

Steps to solve by this approach:

 Step 1: Create a mapping to store the values of each Roman numeral character (I=1, V=5, X=10, L=50, C=100, D=500, M=1000).

 Step 2: Initialize the result to 0.
 Step 3: Iterate through the Roman numeral string from left to right.
 Step 4: For each character, check if its value is less than the value of the next character.
 Step 5: If it is less (like in the case of "IV" where I=1 is less than V=5), subtract the current value from the result.
 Step 6: If it is not less (or if it's the last character), add the current value to the result.
 Step 7: Return the final result after processing all characters.

Submitted Code :