Ctrl K

Value of a Roman Numeral

Easy
Roman numerals still show up on clock faces, chapter headings and old film credits. They are written with seven letters: | Letter | Value | |---|---| | I | 1 | | V | 5 | | X | 10 | | L | 50 | | C | 100 | | D | 500 | | M | 1000 | Letters normally go from largest to smallest and their values add up: XVI = 10 + 5 + 1 = 16. When a smaller letter sits right before a larger one, though, it is subtracted. This happens in exactly six cases: - IV = 4 and IX = 9, - XL = 40 and XC = 90, - CD = 400 and CM = 900. You are given a string numeral holding a correctly written Roman numeral. Return its value.
Example 1
numeral="XLVII" → 47

XL = 40 (the X before L is subtracted), then V = 5 and II = 2, so 47 in total.

Example 2
numeral="MMXXIV" → 2024

MM = 2000, XX = 20, IV = 4, which gives 2024.

Example 3
numeral="CDXC" → 490
Constraints
  • 1 ≤ len(numeral) ≤ 15
  • numeral contains only the letters I, V, X, L, C, D, M
  • numeral is a well-formed Roman numeral for a number from 1 to 3999
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsNumber in Roman Numerals MediumFraction as a Decimal MediumDigits From Scrambled Words MediumSimplify a Letter Polynomial HardPieces With Matching Ends Medium
loading Python…
Input
numeral="XLVII"
Expected
47

Run checks the first 3 tests in your browser. Submit checks all 90 tests on the server, hidden ones included.