#13
Roman to Integer
Easy Look-ahead
- Read
- Understand
- Hints
- Approach
- Solution
- Solved
?The problem
Convert a Roman numeral (I, V, X, L, C, D, M with subtractive pairs like IV and CM) to an integer.
This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗
◎Understanding
Really asking: turn Roman numerals into a number.
Why this works: add each symbol, except when a smaller symbol comes before a bigger one (IV, IX, XL…), then subtract it.
Example: "MCMXCIV"
M +1000, C<M -100, M +1000, X<C -10, C +100, I<V -1, V +5= 1994
✦Hints open one at a time
Usually you add each symbol's value.
If a symbol is smaller than the one after it, subtract it instead.
↗Approach
Map each symbol to its value. Walk left to right: subtract when the next symbol is larger, otherwise add.
</>Solution (Java)
class Solution {
public int romanToInt(String s) {
int total = 0;
for (int i = 0; i < s.length(); i++) {
int v = value(s.charAt(i));
if (i + 1 < s.length() && v < value(s.charAt(i + 1))) total -= v; // e.g. the I in IV
else total += v;
}
return total;
}
private int value(char c) {
switch (c) {
case 'I': return 1;
case 'V': return 5;
case 'X': return 10;
case 'L': return 50;
case 'C': return 100;
case 'D': return 500;
default: return 1000;
}
}
}
!Common mistake
Hard-coding all six subtractive pairs with many if-statements — the "smaller before larger" rule covers them all.
Complexity
- Time: O(n).
- Space: O(1).
Topic: Strings
🎬 Episodes 16–20: video coming soon