Roman to Integer
Easy · hash map
Roman numerals are written with seven symbols: I is 1, V is 5, X is 10, L is 50, C is 100, D is 500 and M is 1000.
A numeral is normally written from the largest symbol to the smallest, and its value is the sum of its symbols, so XVI is 10 + 5 + 1 = 16.
There is one exception. In exactly six cases a smaller symbol is written directly before a larger one, and the pair counts as the larger value minus the smaller: IV is 4, IX is 9, XL is 40, XC is 90, CD is 400 and CM is 900. For example, XLII is 40 + 2 = 42.
Given a well-formed Roman numeral s, return its value as an integer. The symbol M may be repeated any number of times, so large values are possible: MMMM is 4000.
Examples
Example 1
Input: s = "XLII"
Output: 42
XL is 40, then I and I add 2.
Example 2
Input: s = "CMXCIX"
Output: 999
CM is 900, XC is 90 and IX is 9.
Example 3
Input: s = "MMMMV"
Output: 4005
Four Ms are 4000, and V adds 5.
Constraints
- 1 <= len(s) <= 10^4
- s contains only the characters "I", "V", "X", "L", "C", "D" and "M".
- s is a well-formed Roman numeral.