Roman To Integer
To solve this coding challenge, we need to convert a Roman numeral string to its corresponding integer value. The procedure for this involves understanding the rules of Roman numerals and implementing them in pseudocode form.
Explanation
Roman numerals are built using a set of symbols with corresponding integer values. The primary symbols and their values are: Symbol Value- ---- ----- I 1 V 5 X 10 L 50 C 100 D 500 M 1000
Basic Idea:
- Normally, Roman numerals are written from largest to smallest left to right. However, in a few cases, a smaller numeral is placed before a larger numeral to indicate subtraction.
- For example:
- "IV" means 4 because itβs 5 (V) - 1 (I).
- "IX" means 9 because itβs 10 (X) - 1 (I).
- To convert a Roman numeral to an integer, we traverse the string from left to right. If a numeral is smaller than the numeral following it, we subtract it from the total. Otherwise, we add it to the total.
- First, create a dictionary to map Roman numeral symbols to their integer values.
- Initialize a result variable with the value of the last symbol in the string. This is because the last numeral is always added to the result.
- Loop through the string from the second last character to the first character:
-
Initialize
result
result = 5
- Traverse from the second last to the first:
- Check "I" (1):
- Check "C" (100):
- Check "X" (10):
- Continue until the first element.
Detailed Steps in Pseudocode:
-
a. If the current symbol is smaller than the next symbol, subtract its value from the result.
b. Otherwise, add its value to the result.
Pseudocode
# Create a mapping from Roman numerals to integers.
roman_to_integer_map = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
}
# Function to convert Roman numeral to Integer.
function romanToInt(roman_string):
# Initialize result to the value of the last numeral.
result = roman_to_integer_map[roman_string[length of roman_string - 1]]
# Loop through the string from the second last character to the first.
for index from length of roman_string - 2 down to 0:
# If the current numeral is less than the next numeral.
if roman_to_integer_map[roman_string[index]] < roman_to_integer_map[roman_string[index + 1]]:
# Subtract the value of the current numeral from result.
result = result - roman_to_integer_map[roman_string[index]]
else:
# Add the value of the current numeral to result.
result = result + roman_to_integer_map[roman_string[index]]
return result
Let's walk through an example to clarify:
Example: Convert "MCMXCIV"
-
Since 1 (I) < 5 (V), subtract 1 from
result
result = 4
-
Since 100 (C) < 4 (M), subtract 100, now
result = 104
-
Since 10 (X) < 100 (C), subtract 10, now
result = 194