~/problems / Math & matrices

Roman to Integer

easy ~15 min

A museum is cataloguing the dates carved on old buildings. Each date is a Roman numeral built from these symbols:

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

Symbols are normally written from largest to smallest and added up (XVII = 10 + 5 + 1 + 1 = 17). Six pairs instead mean a subtraction, with the smaller symbol written first: IV = 4, IX = 9, XL = 40, XC = 90, CD = 400, CM = 900.

Write roman_value(s) -> int that returns the value of the numeral s.

roman_value("XVII")        # 17
roman_value("XLIX")        # 49
roman_value("MCMXCIV")     # 1994
roman_value("MMMCMXCIX")   # 3999
  • s is a correctly written numeral for a value between 1 and 3999, so 1 <= len(s) <= 15.
  • Aim for O(len(s)) time: one pass over the string.
Show hint

look at each symbol together with the one after it. What does it tell you when a symbol is worth less than its right-hand neighbour?

Topic: Math and matrices. Digit-by-digit arithmetic, matrix rotation and in-place tricks.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc