Roman to Integer

Medium~15 min

Given a string s representing a Roman numeral, convert it to an integer.

Roman numeral symbols and their values:

| Symbol | Value | |--------|-------| | I | 1 | | V | 5 | | X | 10 | | L | 50 | | C | 100 | | D | 500 | | M | 1000 |

Roman numerals are usually written largest to smallest from left to right. However, there are six subtractive cases:

  • IV = 4, IX = 9
  • XL = 40, XC = 90
  • CD = 400, CM = 900

When a smaller value appears before a larger value, it is subtracted instead of added.

Examples

Example 1
Input: s = "III"
Output: 3
Explanation: I + I + I = 3.
Example 2
Input: s = "LVIII"
Output: 58
Explanation: L = 50, V = 5, III = 3. Total = 58.
Example 3
Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90, IV = 4. Total = 1994.

Constraints

  • 1 <= s.length <= 15
  • s contains only the characters I, V, X, L, C, D, M
  • s is a valid Roman numeral in the range [1, 3999]
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run