← Back to libraryQuestion 128 of 273
⌨️Java CodingIntermediate

Convert a Roman Numeral to an Integer

📌 Definition:

Convert a Roman numeral string to its integer value (e.g. "MCMXciv" -> 1994). Symbols usually add, but a smaller symbol before a larger one subtracts.

📖 Detailed Explanation:

Map each symbol to its value and scan left to right: if the current symbol is smaller than the next, subtract it (handles IV, IX, XL, etc.); otherwise add it. One pass, O(n) time. The subtractive rule is the only subtlety.

💻 Solutions:
public static int romanToInt(String s) {
    Map<Character,Integer> map = Map.of(
        'I', 1, 'V', 5, 'X', 10, 'L', 50, 'C', 100, 'D', 500, 'M', 1000);
    int total = 0;
    for (int i = 0; i < s.length(); i++) {
        int curr = map.get(s.charAt(i));
        if (i + 1 < s.length() && curr < map.get(s.charAt(i + 1))) total -= curr;
        else total += curr;
    }
    return total;
}
function romanToInt(s) {
  const map = { I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000 };
  let total = 0;
  for (let i = 0; i < s.length; i++) {
    const curr = map[s[i]];
    if (i + 1 < s.length && curr < map[s[i + 1]]) total -= curr;
    else total += curr;
  }
  return total;
}
def roman_to_int(s):
    values = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
    total = 0
    for i, ch in enumerate(s):
        if i + 1 < len(s) and values[ch] < values[s[i + 1]]:
            total -= values[ch]
        else:
            total += values[ch]
    return total
🔑 Key Points:
  • Map symbols to values
  • Subtract when current < next, else add
  • Single left-to-right pass
  • O(n) time, O(1) space
🌍 Real-World Example:

Parsing with a look-ahead rule (subtract vs add) mirrors tokenizing formats where a symbol's meaning depends on its neighbor — a light parsing exercise.

🎯 Scenario-Based Interview Question:

How does your code handle the subtractive cases like "IV" (4) and "IX" (9)?