
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.
1import java.util.HashMap;
2import java.util.Map;
3
4public class RomanToInt {
5 public int romanToInt(String s) {
6 Map<Character, Integer> values = new HashMap<>();
7 values.put('I', 1);
8 values.put('V', 5);
9 values.put('X', 10);
10 values.put('L', 50);
11 values.put('C', 100);
12 values.put('D', 500);
13 values.put('M', 1000);
14
15 int total = 0;
16 for (int i = 0; i < s.length(); i++) {
17 if (i + 1 < s.length() && values.get(s.charAt(i)) < values.get(s.charAt(i + 1))) {
18 total -= values.get(s.charAt(i));
19 } else {
20 total += values.get(s.charAt(i));
21 }
22 }
23
24 return total;
25 }
26
27 public static void main(String[] args) {
28 RomanToInt converter = new RomanToInt();
29 System.out.println(converter.romanToInt("MCMXCIV")); // Output: 1994
30 }
31}This Java solution uses a HashMap to store Roman numeral values. The traversal logic is similar to the C/C++ methods, using subtraction for certain numeral pairs.
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.