
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).
1using System;
using System.Collections.Generic;
class RomanToIntReverse {
public int RomanToIntFromRight(string s) {
Dictionary<char, int> values = new Dictionary<char, int> {
{'I', 1}, {'V', 5}, {'X', 10}, {'L', 50},
{'C', 100}, {'D', 500}, {'M', 1000}
};
int total = 0;
int last_value = 0;
for (int i = s.Length - 1; i >= 0; i--) {
int current_value = values[s[i]];
if (current_value < last_value) {
total -= current_value;
} else {
total += current_value;
}
last_value = current_value;
}
return total;
}
static void Main(string[] args) {
RomanToIntReverse converter = new RomanToIntReverse();
Console.WriteLine(converter.RomanToIntFromRight("LVIII")); // Output: 58
}
}This C# code uses a reverse loop over the input, enabling each Roman numeral to be considered in relation to its successor, allowing clear decision-making for increments or decrements.