Problem Description
Given a string representing a Roman numeral, convert it to its integer equivalent. Roman numerals are represented by seven symbols, and in some cases, a smaller numeral appears before a larger numeral to indicate subtraction. For example, "MCMXCIV" converts to 1994.
Key Insights
- Map each Roman numeral character to its integer value using a hash table or dictionary.
- Loop through the string and check if the current numeral is less than the next numeral; if so, subtract its value.
- Otherwise, add its value to the total.
- This approach takes advantage of the subtractive notation used in Roman numerals.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the input string. Space Complexity: O(1), since the mapping and additional variables use constant space.
Solution
We use a dictionary (or hash map) to store the values of each Roman numeral. As we iterate over the string, we compare the current numeral's value with the next numeral's value. When a numeral of smaller value appears before a numeral of larger value, we subtract the current numeral's value; otherwise, we add it. This technique efficiently handles both the standard and subtractive cases in one pass through the string.