
Sponsored
Sponsored
The key idea is to traverse the given Roman numeral string from left to right. As we process each character, we compare it with the next one. If the current character has a smaller value than the next one, it means we are in a subtraction scenario (like IV = 4), so we subtract the value of the current character. Otherwise, we add its value.
Time Complexity: O(n), where n is the length of the string, because we make one pass through the string.
Space Complexity: O(1), constant space as the dictionary size does not depend on the input.
1def romanToInt(s: str) -> int:
2 values = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
3 total = 0
4 for i in range(len(s)):
5 if i + 1 < len(s) and values[s[i]] < values[s[i + 1]]:
6 total -= values[s[i]]
7 else:
8 total += values[s[i]]
9 return total
10
11print(romanToInt('MCMXCIV')) # Output: 1994The Python solution uses a dictionary to map Roman characters to integers. It scans the string, adding or subtracting values based on the adjacency conditions.
In this approach, we traverse the string from right to left. We add the value of the current character to the total if it is greater or equal to its previous character; otherwise, we subtract it. Reverse traversal helps us intuitively handle the subtraction rule.
Time Complexity: O(n).
Space Complexity: O(1).
1#
This C program reverses the logic, starting from the end of the string and using a variable to remember the last checked value to determine whether to add or subtract.