Skip to the content

Roman numerals

Problem

The column in the forum still carries its inscription, and the tour guide has to read it out loud to the visitors. The year is in Roman numerals. Write a function that takes a text with a Roman numeral and returns its value as an integer. Each symbol is worth: I 1, V 5, X 10, L 50, C 100, D 500 and M 1000. You read from left to right and each symbol adds its value, except when the symbol right after it is worth more: then it subtracts. So IV is 4, IX is 9, XL is 40, XC is 90, CD is 400 and CM is 900. The last symbol always adds.

For example, CCXLIX is 100 + 100 - 10 + 50 - 1 + 10 = 249.

The text is always a valid Roman numeral, in capitals, from 1 to 3999: there is no need to check it.

Examples

  • The one in the example

    "CCXLIX" → 249

  • Only additions

    "MDCLXVI" → 1666

  • One subtraction

    "IV" → 4

  • Equal symbols in a row

    "LVIII" → 58

  • Two subtractions

    "XCIX" → 99

Besides these, the challenge has hidden tests that are revealed when you submit your solution.

You start with this

Python

def read_roman(numeral):
    pass

JavaScript

function readRoman(numeral) {
}
Solve this challenge

It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.

More O(n) challenges

See all challenges →