
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.
- We break down "LVIII" as "L" + "V" + "III".
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.
- We break down "MCMXCIV" as "M" + "CM" + "XC" + "IV".
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)
Editorial
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. |
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