
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.
1using System;
2using System.Collections.Generic;
3
4class RomanToInt {
5 public int RomanToIntFunc(string s) {
6 Dictionary<char, int> values = new Dictionary<char, int> {
7 {'I', 1}, {'V', 5}, {'X', 10}, {'L', 50},
8 {'C', 100}, {'D', 500}, {'M', 1000}
9 };
10
11 int total = 0;
12 for (int i = 0; i < s.Length; i++) {
13 if (i + 1 < s.Length && values[s[i]] < values[s[i + 1]]) {
14 total -= values[s[i]];
15 } else {
16 total += values[s[i]];
17 }
18 }
19
20 return total;
21 }
22
23 static void Main(string[] args) {
24 RomanToInt converter = new RomanToInt();
25 Console.WriteLine(converter.RomanToIntFunc("LVIII")); // Output: 58
26 }
27}C# implementation uses a Dictionary for Roman numeral values. It iteratively adds or subtracts values as it processes the Roman numeral string.
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#include <iostream>
#include <unordered_map>
int romanToIntFromRight(const std::string& s) {
std::unordered_map<char, int> values = {{'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;
}
int main() {
std::string roman = "LVIII";
std::cout << romanToIntFromRight(roman) << std::endl; // Output: 58
return 0;
}The C++ code builds a reverse traversal to take advantage of looking at the last seen value for whether to sum or differ.