Roman to Integer
Easy
Topics
Given a Roman numeral string s, convert it to an integer. Symbols: I=1, V=5, X=10, L=50, C=100, D=500, M=1000. A smaller symbol before a larger one is subtracted (e.g., IV = 4).
Example 1
III = 3.Input: s = "III" Output: 3
Example 2
Input: s = "LVIII" Output: 58
Example 3
Input: s = "MCMXCIV" Output: 1994
Constraints
- 1 <= s.length <= 15
- s is a valid Roman numeral in the range [1, 3999].
Editorial — intuition, approach, complexity and pitfalls
Intuition
Roman numerals are additive except for six subtractive pairs — IV, IX, XL, XC, CD, CM. The obvious implementation special-cases those six by peeking at two characters at a time.
There is a cleaner rule that covers all six without naming any of them: a symbol is subtracted exactly when a strictly smaller value precedes a larger one. That is the defining property of the subtractive pairs, so one left-to-right scan with a single lookahead handles every case.
MCMXCIV
M 1000, next C is smaller -> add 1000
C 100, next M is larger -> subtract -100
M 1000, next X is smaller -> add 1000
X 10, next C is larger -> subtract -10
C 100, next I is smaller -> add 100
I 1, next V is larger -> subtract -1
V 5, last character -> add 5
----
1994Approach
- Map each symbol to its value.
- For each position, subtract its value if the next symbol is strictly larger, else add it.
Dry Run
s = "LVIII"
L 50, next V smaller -> +50 total 50
V 5, next I smaller -> +5 total 55
I 1, next I equal -> +1 total 56
I 1, next I equal -> +1 total 57
I 1, last -> +1 total 58
answer 58 note "equal" adds, which is why the
comparison must be strictComplexity
- Time — O(n): one pass, and the input is capped at 15 characters.
- Space — O(1): the symbol table has seven fixed entries.
Common Pitfalls
- Using
<=instead of<for the lookahead. Equal neighbours like theIIIinLVIIImust add, and<=would subtract them. - Reading past the end on the final character. Guard the lookahead with an index check.
- Hard-coding the six subtractive pairs. It works, but it is more code and it obscures the single rule that generates them.
- Assuming the input might be malformed. The constraints promise a valid numeral in [1, 3999], so no validation is required — but say so rather than silently relying on it.
Full Solution — all languages
class Solution:
def romanToInt(self, s):
val = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
total = 0
for i in range(len(s)):
if i + 1 < len(s) and val[s[i]] < val[s[i + 1]]:
total -= val[s[i]]
else:
total += val[s[i]]
return totalimport java.util.*;
class Solution {
public int romanToInt(String s) {
Map<Character,Integer> val = new HashMap<>();
val.put('I',1);
val.put('V',5);
val.put('X',10);
val.put('L',50);
val.put('C',100);
val.put('D',500);
val.put('M',1000);
int total = 0;
for (int i = 0; i < s.length(); i++) {
if (i + 1 < s.length() && val.get(s.charAt(i)) < val.get(s.charAt(i + 1))) total -= val.get(s.charAt(i));
else total += val.get(s.charAt(i));
}
return total;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int romanToInt(string s) {
unordered_map<char,int> val = { {
'I',1
},
{
'V',5
},
{
'X',10
},
{
'L',50
},
{
'C',100
},
{
'D',500
},
{
'M',1000
}
};
int total = 0;
for (int i = 0; i < (int)s.size(); i++) {
if (i + 1 < (int)s.size() && val[s[i]] < val[s[i + 1]]) total -= val[s[i]];
else total += val[s[i]];
}
return total;
}
};/**
* @param {string} s
* @return {number}
*/ var romanToInt = function(s) {
const val = { 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++) {
if (i + 1 < s.length && val[s[i]] < val[s[i + 1]]) total -= val[s[i]];
else total += val[s[i]];
}
return total;
};