Convert a Roman Numeral to an Integer
Implement romanToInt
Given a Roman numeral string
s, convert it to its integer value. Roman numerals are normally written largest-to-smallest left to right — but six specific pairs (IV, IX, XL, XC, CD, CM) flip that: a smaller symbol placed just before a larger one means subtract instead of add.
Looking up each symbol's value with a chain of if/else comparisons works, but it's the kind of lookup a hash mapHash MapA data structure that maps keys to values with O(1) average lookup time, instead of scanning through a list or chain of comparisons. was built for: build the 7 symbol-to-value pairs once, and every subsequent lookup becomes a single O(1) step. The core trick — comparing each symbol's value against the one right after it — stays the same either way: if the current symbol is smaller than the next one, it's part of a subtractive pair.
Example 1:
Input: s = "MCMXCIV"
Output: 1994
Example 2:
Input: s = "III"
Output: 3
Example 3:
Input: s = "LVIII"
Output: 58
+ 9 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ s.length ≤ 15 - ●
s is a valid Roman numeral in the range [1, 3999] - ●
Symbols used: I(1), V(5), X(10), L(50), C(100), D(500), M(1000)
s =
MCMXCIV