Python: Convert a Roman numeral to an integer:
This is a Python program that converts the given Roman numeral into an integer.
Code:
def roman_to_int(s):
rom_val = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
int_val = 0
for i in range(len(s)):
if i > 0 and rom_val[s[i]] > rom_val[s[i - 1]]:
int_val += rom_val[s[i]] - 2 * rom_val[s[i - 1]]
else:
int_val += rom_val[s[i]]
return int_val
print(roman_to_int('MVI'))
print(roman_to_int('MXIV'))
print(roman_to_int('C'))
Output:
1006
1014
100
Explanation:
This code defines a method called roman_to_int() that takes a string of Roman numerals as an argument and returns the corresponding integer value.
Inside the method, a dictionary named rom_val is defined which maps each Roman numeral character to its corresponding integer value. An integer variable int_val is initialized to 0.
Then, a for loop is used to iterate over each character in the input string s. Inside the loop, an if statement is used to check if the current character is greater than the previous character, which indicates that the current character is part of a subtraction such as IV or IX. If this is the case, the value of the current character is added to int_val, and the value of the previous character is subtracted twice. This is because the previous character was already added to int_val in the previous iteration of the loop, so it needs to be subtracted twice to cancel out the previous addition and to subtract the value of the previous character as well. If the current character is not greater than the previous character, then its value is simply added to int_val.
Finally, the int_val variable is returned as the output of the roman_to_int() method.