
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)
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 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