Roman to Integer
EasyGiven a Roman numeral string, convert it to an integer. Roman numerals are represented by: I=1, V=5, X=10, L=50, C=100, D=500, M=1000. When a smaller numeral appears before a larger one, subtract it.
Examples
| Input | Output |
|---|---|
| s = "III" | 3 |
| s = "MCMXCIV" | 1994 |
Python Solution
def roman_to_int(s: str) -> int:
values = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
total = 0
prev = 0
for c in reversed(s):
v = values[c]
total += v if v >= prev else -v
prev = v
return totalJavaScript Solution
function romanToInt(s) {
const values = { I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000 };
let total = 0, prev = 0;
for (let i = s.length - 1; i >= 0; i--) {
const v = values[s[i]];
total += v >= prev ? v : -v;
prev = v;
}
return total;
}Step-by-Step Explanation
- Process from right to left. If current value < previous, subtract; else add.
- This handles cases like IV (4) and IX (9) correctly.
Complexity Analysis
| Time | O(n) |
| Space | O(1) |
Tags
StringMath
Related Problems
Related Tools
All Problems
Two SumReverse a StringPalindrome CheckFizzBuzzBinary SearchReverse Linked ListMerge Two Sorted ArraysValid ParenthesesMaximum Subarray (Kadane's Algorithm)Remove Duplicates from Sorted ArrayNth Fibonacci NumberValid AnagramFirst Unique CharacterClimbing StairsBest Time to Buy and Sell StockContains DuplicateMove ZeroesIntersection of Two ArraysLongest Common Prefix