
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.
1function romanToInt(s) {
2 const values = {
3 'I': 1,
4 'V': 5,
5 'X': 10,
6 'L': 50,
7 'C': 100,
8 'D': 500,
9 'M': 1000
10 };
11
12 let total = 0;
13 for (let i = 0; i < s.length; i++) {
14 if (i + 1 < s.length && values[s[i]] < values[s[i + 1]]) {
15 total -= values[s[i]];
16 } else {
17 total += values[s[i]];
18 }
19 }
20
21 return total;
22}
23
24console.log(romanToInt('MCMXCIV')); // Output: 1994This JavaScript version uses an object to store the numeral values. The function iterates through the string and performs addition or subtraction as required based on the character 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.