Skip to content
BytePatterns

Roman Numeral to Integer

EasyStrings#string-scan#lookup-table~15m

Problem

A museum catalogue stores years as Roman numerals and needs them as integers. The symbols are I = 1, V = 5, X = 10, L = 50, C = 100, D = 500 and M = 1000, written from largest to smallest and added up, except that a smaller symbol placed right before a larger one is subtracted, as in IV = 4 or CM = 900. Given a valid numeral for a value from 1 to 3999, return its value.

Examples

Input:  s = "LVIII"
Output: 58
Why:    L + V + I + I + I = 50 + 5 + 3
Input:  s = "MCMXCIV"
Output: 1994
Why:    M = 1000, CM = 900, XC = 90, IV = 4
Input:  s = "IV"
Output: 4
Why:    edge case, the whole numeral is a single subtractive pair

Hints

0 / 3

Stuck on the idea rather than the code? String Basics covers it.