
Problem
Solution
Submissions
Convert Roman to Integer
Certification: Basic Level
Accuracy: 0%
Submissions: 0
Points: 5
Write a JavaScript program to convert a Roman numeral string to its integer equivalent. Roman numerals are represented by seven symbols: I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1000. Roman numerals are usually written from largest to smallest from left to right. However, in some cases, a smaller numeral appears before a larger one to indicate subtraction (e.g., IV = 4, IX = 9).
Example 1
- Input: s = "LVIII"
- Output: 58
- Explanation:
- Break down the Roman numeral: L = 50, V = 5, I = 1, I = 1, I = 1.
- Since all symbols are in descending order, simply add them.
- 50 + 5 + 1 + 1 + 1 = 58.
- Therefore, "LVIII" equals 58.
- Break down the Roman numeral: L = 50, V = 5, I = 1, I = 1, I = 1.
Example 2
- Input: s = "MCMXC"
- Output: 1990
- Explanation:
- Break down the Roman numeral: M = 1000, C = 100, M = 1000, X = 10, C = 100.
- CM represents 1000 - 100 = 900 (subtraction case).
- XC represents 100 - 10 = 90 (subtraction case).
- M + CM + XC = 1000 + 900 + 90 = 1990.
- Therefore, "MCMXC" equals 1990.
- Break down the Roman numeral: M = 1000, C = 100, M = 1000, X = 10, C = 100.
Constraints
- 1 ≤ s.length ≤ 15
- s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M')
- It is guaranteed that s is a valid Roman numeral in the range [1, 3999]
- Time Complexity: O(n)
- 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 of Roman symbols to their integer values
- Iterate through the string from left to right
- For each character, check if the next character represents a larger value
- If the current value is smaller than the next, subtract it (subtraction case)
- Otherwise, add the current value to the result
- Handle the last character separately as it has no next character