/13. Roman to Integer

13. Roman to Integer

Easy
Hash Table66.3% acceptance

Given a string roman_numeral consisting of characters I, V, X, L, C, D, and M, representing a valid Roman numeral in the range [1, 3999], return its integer value. Roman numerals use subtractive notation for certain values: I before V or X means 4 or 9, X before L or C means 40 or 90, C before D or M means 400 or 900. The input is guaranteed to be valid.

Example 1

Input: "XCIII"

Output: 93

Explanation: X = 10, C = 100, so XC = 90, III = 3. 90 + 3 = 93.

Example 2

Input: "CDXLIV"

Output: 444

Explanation: CD = 400, XL = 40, IV = 4. 400 + 40 + 4 = 444.

Example 3

Input: "MMXXI"

Output: 2021

Explanation: MM = 2000, XXI = 21. 2000 + 21 = 2021.

Constraints

  • 1 <= len(roman_numeral) <= 15
  • roman_numeral contains only characters I, V, X, L, C, D, M
  • roman_numeral is a valid Roman numeral representing an integer in [1, 3999]
Python (current runtime)

Case 1

Input: "DCCC"

Expected: 800

Case 2

Input: "XLIX"

Expected: 49

Case 3

Input: "CCVII"

Expected: 207

Case 4

Input: "MMDCCLXXVII"

Expected: 2777

Case 5

Input: "IV"

Expected: 4