class RomanToInteger:
def __init__(self):
self.values = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
def roman_to_int(self, s: str) -> int:
total = 0
for i in range(len(s)):
value = self.values[s[i]]
if i + 1 < len(s) and self.values[s[i]] < self.values[s[i + 1]]:
total -= value # subtract if smaller before bigger
else:
total += value # add otherwise
return total
# Driver code
converter = RomanToInteger()
result = converter.roman_to_int('MCMIV')
print(result)iterate over each Roman numeral character
value = self.values[s[i]]
get integer value of current Roman numeral
if i + 1 < len(s) and self.values[s[i]] < self.values[s[i + 1]]:
check if current value is less than next value to decide subtraction
total -= value # subtract if smaller before bigger
subtract current value from total
otherwise add current value
total += value # add otherwise
add current value to total