Question: Roman numerals are represented by seven different symbols: IVXLCD and M.

Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000

For example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

  • I can be placed before V (5) and X (10) to make 4 and 9. 
  • X can be placed before L (50) and C (100) to make 40 and 90. 
  • C can be placed before D (500) and M (1000) to make 400 and 900.

Given a roman numeral, convert it to an integer.

How to Solve: This is definitely one of those problems that is labeled easy, but looked like an insurmountable force when first looking at it. My biggest struggle was to understand how to do the checks without getting an out of range error.

Basically, I knew that we would have to constantly compare whatever numeral we’re at to the next one, but would run into errors when getting to the end of the list. One of the answers I read was able to solve this pretty nicely, so here’s what we’re going to have to do;

  1. Create a mapping (dictionary) of all the numerals and their worth.
  2. Create a variable to keep track of cost, initialize it to 0.
  3. Use a for loop from 0 to the length of the string, s.
  4. Check for two conditions:
    1. The numeral is less than the numeral after it AND
    2. The numeral is not the last one in the string
  5. If both are true, that must mean the numeral we’re using is going to subtract some amount, like in the three scenarios discussed above. If so, take away that amount instead of adding it.
  6. If one is false, add the numeral like normal.
  7. Return the new amount after the loop is done.

Answer:

m = {
	'I': 1,
	'V': 5,
	'X': 10,
	'L': 50,
	'C': 100,
	'D': 500,
	'M': 1000
}


ans = 0

for i in range(len(s)):
	if i < len(s) - 1 and m[s[i]] < m[s[i+1]]:
		ans -= m[s[i]]
	else:
		ans += m[s[i]]
		
return ans