/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 are written according to standard rules, including subtractive notation (e.g., IV = 4, IX = 9, XL = 40, XC = 90, CD = 400, CM = 900).

Example 1

Input: roman_numeral=XCIII

Output: 93

Explanation: XC = 90, III = 3, so 90 + 3 = 93.

Example 2

Input: roman_numeral=CDXLIV

Output: 444

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

Example 3

Input: roman_numeral=MMXXI

Output: 2021

Explanation: MM = 2000, XXI = 21, so 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: roman_numeral='DCCCXC'

Expected: 890

Case 2

Input: roman_numeral='LXXVII'

Expected: 77

Case 3

Input: roman_numeral='MMDCCCLXXXVIII'

Expected: 2888

Case 4

Input: roman_numeral='CXXIV'

Expected: 124

Case 5

Input: roman_numeral='IX'

Expected: 9