Educatifu
Open menu

Roman to Integer

Mediumstringsmath

Convert a Roman numeral to its integer value. The symbols are I=1, V=5, X=10, L=50, C=100, D=500, M=1000. A smaller symbol placed before a larger one is subtracted (e.g. IV = 4, IX = 9).

Input

A single line: a valid Roman numeral in upper case.

Output

Its integer value.

Examples

Example 1

Input
III
Output
3

1 + 1 + 1 = 3.

Example 2

Input
IX
Output
9

I before X means 10 - 1 = 9.

Example 3

Input
MCMXCIV
Output
1994

1000 + 900 + 90 + 4 = 1994.

Constraints

  • The numeral is valid and represents a number from 1 to 3999.

Hints

Reveal hint 1

Give each symbol its value, then walk left to right.

Reveal hint 2

If the current symbol is worth less than the one after it, subtract it; otherwise add it.

Reference solution (spoiler — try it yourself first)

Approach

Map each symbol to its value; for each position, subtract it when the next symbol is larger, otherwise add it.

s = input()
v = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
t = 0
for i, ch in enumerate(s):
    if i + 1 < len(s) and v[ch] < v[s[i + 1]]:
        t -= v[ch]
    else:
        t += v[ch]
print(t)

← All practice problems

Bring us the problem, not a perfect specification

Tell us what needs to change, who it affects and any important deadline. We will review the context and reply with useful next questions.

  1. 01Share contextDescribe the workflow, constraint or risk.
  2. 02Clarify togetherWe identify missing facts and useful options.
  3. 03Choose a startAgree a focused assessment or delivery step.
Start a conversation