Skip to content
UniCircle
EasyCodingGreedy conversion and parsing

Convert between Roman numerals and integers (both ways)

Question PROG-CNV-104

Each line holds either an integer from 1 to 3999 or a Roman numeral in standard form. Convert integers to Roman numerals, and Roman numerals to integers.

Roman symbols: I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1000. Standard form uses the six subtractive pairs IV (4), IX (9), XL (40), XC (90), CD (400) and CM (900). For example, 1994 = MCMXCIV.

Constraints

  • 1 ≤ T ≤ 2000
  • Integers are between 1 and 3999. Roman numerals are valid and in standard form.

Input and output

Input
First line: T. Then T lines, each an integer or an uppercase Roman numeral.
Output
T lines with the converted values.

Examples

Input 1

4
1994
MCMXCIV
58
IX

Output

MCMXCIV
1994
LVIII
9

1994 = M + CM + XC + IV. 58 = L + V + III.

Input 2

2
3999
MMMCMXCIX

Output

MMMCMXCIX
3999

The largest value in standard form, in both directions.

Show hints
  • Integer to Roman: go through a table of the 13 values (1000, 900, 500, 400, …, 1) from largest to smallest, and take each value as many times as it fits.
  • Roman to integer: a symbol is subtracted when a larger symbol follows it.
Show the explanation

Integer → Roman (greedy). With the table M 1000, CM 900, D 500, CD 400, C 100, XC 90, L 50, XL 40, X 10, IX 9, V 5, IV 4, I 1, repeatedly append the largest symbol that still fits and subtract its value. Putting the subtractive pairs in the table is the key idea, because it removes all special cases. Greedy is correct here because the Roman system is designed so that the largest-first choice always gives the standard form.

Roman → integer. Scan from left to right. Add each symbol's value, except subtract it when the next symbol is larger (the I in IV, the C in CM). An equivalent version scans right to left and subtracts any symbol smaller than the largest seen so far.

Telling them apart: a line that starts with a digit is an integer.

Complexity: O(length) per line. Every result has at most 15 characters (3888 = MMMDCCCLXXXVIII).

Follow-ups: validate input, rejecting forms like IIII, VX or IC (one approach: convert, convert back, and compare), and explain why 3999 is the usual limit: standard notation has no symbol above M.

Original UniCircle question. Last reviewed 22 Oct 2026.