Problem 318315 · medium · Phase 03 Linear Management & Searching

Read a Roman Numeral

strings · lookup tables · subtractive notation

A museum catalogue records years as Roman numerals using the symbols I=1, V=5, X=10, L=50, C=100, D=500, M=1000. Symbols are normally written from largest to smallest and added; but when a smaller symbol appears immediately before a larger one (IV, IX, XL, XC, CD, CM) it is subtracted instead. Given a valid numeral s, return its integer value.

Examples

Input:  s = "MMXXVI"
Output: 2026

Input:  s = "CDXLIV"
Output: 444
Explanation: CD = 400, XL = 40, IV = 4.

Constraints

  • 1 <= len(s) <= 15, value between 1 and 3999
  • Target: O(len(s)) time.

Goals

  • Map symbols to values with a dictionary
  • Detect subtractive pairs by comparing a symbol with the one after it
  • Handle the last symbol without an out-of-range lookup
Starting Python…