Convert a Roman numeral string to an integer.
Problem Statement
Examples
Input: s = "III"
Output: 3
Explanation: Converting the Roman numeral values yields integer 3.
Input: s = "LVIII"
Output: 58
Explanation: Converting the Roman numeral values yields integer 58.
Input: s = "MCMXCIV"
Output: 1994
Explanation: Converting the Roman numeral values yields integer 1994.
Complexity
Time Complexity: O(N)
Space Complexity: O(1)
Hints
Editorial & Approach
Problem Overview & Intuition
In Roman numerals, smaller values preceding larger values indicate subtraction (e.g., IV = 4, IX = 9). Otherwise, values are additive. Comparing values[s[i]] with values[s[i+1]] solves the conversion in a single linear pass.
Step-by-Step Approach
- Create symbol map for I=1, V=5, X=10, L=50, C=100, D=500, M=1000.
- Iterate
ifrom0tos.length - 1. - If
values[s[i]] < values[s[i + 1]], subtractvalues[s[i]]fromtotal. - Else add
values[s[i]]tototal. - Return
total.
Optimal Implementation (JavaScript)
function romanToInt(s) {
const values = { I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000 };
let total = 0;
for (let i = 0; i < s.length; i++) {
const current = values[s[i]];
const next = values[s[i + 1]] || 0;
if (current < next) {
total -= current;
} else {
total += current;
}
}
return total;
}
Complexity Analysis
Edge Cases & Corner Traps Handled
- Single symbol: "I" -> 1, "M" -> 1000.
- Subtractive combinations: "IV", "IX", "XL", "XC", "CD", "CM".