KatInterview

Decode an Ancient Numeral String into a Number

StringsAuto-graded · 24 test cases
EasyAuto-gradedStringsstringshash-mapparsing

Last updated

Parse a valid Roman numeral string into its integer value by handling additive symbols and the six subtractive pairs.

Decode an Ancient Numeral String into a Number

A scribe records whole numbers using seven letters, each worth a fixed amount:

LetterWorth
I1
V5
X10
L50
C100
D500
M1000

Letters are normally written from the largest worth to the smallest, reading left to right, and the worths are added together. There is one exception: to express certain values, a smaller letter is written immediately before a larger one, and in that case the smaller letter's worth is subtracted instead of added. Exactly six such combinations exist:

  • I before V gives 4, and I before X gives 9.
  • X before L gives 40, and X before C gives 90.
  • C before D gives 400, and C before M gives 900.

For example, 4 is written IV (not IIII), and 1994 is written MCMXCIV, which reads as M + CM + XC + IV = 1000 + 900 + 90 + 4.

Task

Given a string numeral containing a valid numeral written this way, return the integer it represents.

Constraints

  • 1 <= len(numeral) <= 15
  • numeral consists only of the characters I, V, X, L, C, D, M.
  • numeral is guaranteed to be a valid numeral whose value lies in the range [1, 3999].
  • The function returns a single integer.

Examples

Example 1

Input: decode_numeral('III')

Output: 3

Example 2

Input: decode_numeral('MCMXCIV')

Output: 1994

Example 3

Input: decode_numeral('LVIII')

Output: 58

Example 4

Input: decode_numeral('IX')

Output: 9

Hints

Hint 1

Start with a lookup table that maps each letter to its worth, so you can convert characters to numbers in constant time.

Hint 2

A subtractive pair such as CM equals M minus C. Instead of recognizing pairs as units, decide for each letter on its own whether it is added or subtracted.

Hint 3

Compare each letter's worth with the worth of the letter right after it: if it is strictly smaller, subtract it, otherwise add it. Take care at the last character, which has no successor.