Skip to main content

Exercise 10: Roman Numeral to Integer

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. The conversion of symbol to value is given in the following chart:

SymbolValue
I1
V5
X10
L50
C100
D500
M1000

A Roman numeral is formed by appending the conversions of decimal place values from highest to lowest. For example, 3 is written as III in Roman numeral -- three ones added together. 23 is written as XXIII, which is simply XX + III. The number 57 is written as LVII, which is L + V + II.

Roman numerals are usually written largest value symbol to smallest value symbol, from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. A one is before a five indicates the subtractive form, it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

  • I can be placed before V (5) and X (10) to make 4 and 9.

  • X can be placed before L (50) and C (100) to make 40 and 90.

  • C can be placed before D (500) and M (1000) to make 400 and 900.

Given a string containing a Roman numeral between I and MMMCMXCIX, return an integer of the value it represents.

Input: 'IV'
Output: 4

Input: 'LVIII'
Output: 58

Input: 'MMMCMXCIX'
Output: 3999

Sketch:

Script: