Roman to Integer

Easy Math & Geometry AI round

Roman numerals write a number with seven letters, each worth a value: I is 1, V is 5, X is 10, L is 50, C is 100, D is 500 and M is 1000.

The letters usually go from larger values to smaller ones, and the number is the sum of their values: MDCLXVI is 1000 + 500 + 100 + 50 + 10 + 5 + 1 = 1666. Six pairs are written the other way round, a smaller letter just before a larger one, and stand for the larger value less the smaller: IV is 4, IX is 9, XL is 40, XC is 90, CD is 400 and CM is 900.

Return the number that the numeral s stands for.

Example 1

Input: s = "CDXLIV"
Output: 444

CD is 500 - 100 = 400, XL is 50 - 10 = 40 and IV is 5 - 1 = 4: in each pair a smaller letter comes before a larger one, so 400 + 40 + 4 = 444.

Example 2

Input: s = "DCCVII"
Output: 707

Example 3

Input: s = "MMCMLXXXIX"
Output: 2989

Constraints

  • 1 ≤ s.length ≤ 15
  • s is the usual Roman numeral of a number from 1 to 3999: its thousands, hundreds, tens and ones in that order, each written as above

More Math & Geometry

All Math & Geometry problems