Problem 62
Roman to Integer
Easy · 10 pts · String, Math, Hash Table
Problem
Convert a Roman numeral to an ordinary integer. The symbols are I = 1, V = 5, X = 10, L = 50, C = 100, D = 500 and M = 1000. Normally symbols are written from largest to smallest and their values are added, as in XII = 10 + 1 + 1 = 12. When a smaller symbol comes right before a larger one, it is subtracted instead. This happens in six cases: IV = 4, IX = 9, XL = 40, XC = 90, CD = 400 and CM = 900. So while reading left to right, subtract a symbol's value if the next symbol is larger, and add it otherwise. For example, MCMXCIV = 1000 + 900 + 90 + 4 = 1994.
Input
A single valid Roman numeral.
Output
Print its integer value.
Constraints
The value is between 1 and 3999.
Example input
III
Example output
3
Explanation
"III" consists of three I's. No symbol is followed by a larger one, so all values are added: 1 + 1 + 1 = 3.