Skills101
← All coding problems

Roman Numeral to Integer

easyStrings II+10 XPTime limit 2s

Old clock faces and book chapters use Roman numerals: I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1000. Symbols are normally written from largest to smallest and added up (XVI = 16), but six pairs use subtraction: IV = 4, IX = 9, XL = 40, XC = 90, CD = 400, CM = 900. So MCMXCIV = 1000 + 900 + 90 + 4 = 1994.

Convert each numeral to an ordinary number.

Input:

  • line 1: q
  • next q lines: one valid Roman numeral each (standard form, value 1 to 3999)

Output: q lines — the value of each numeral.

Constraints: 1 ≤ q ≤ 10⁴.

Think about it: scan left to right. If a symbol is smaller than the one after it, subtract it; otherwise add it.

Sample input 1

3
XVI
MCMXCIV
IV

Sample output 1

16
1994
4

Sample input 2

2
I
MMMCMXCIX

Sample output 2

1
3999

Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).

Loading editor…

Log in to run and submit your code — it's free.