Skip to content
thesarfo

Reference

Roman to Integer

Converting a Roman numeral string to an integer using a symbol-value map and the subtract-if-smaller-comes-before-larger rule.

views 0

Convert a Roman numeral string to an integer. (LeetCode problem)

Symbols: I=1, V=5, X=10, L=50, C=100, D=500, M=1000. Roman numerals are usually written largest-to-smallest left-to-right, but a smaller numeral before a larger one means subtract: IV=4 (5-1), IX=9 (10-1), XL=40 (50-10), XC=90 (100-10), CD=400 (500-100), CM=900 (1000-100).

Approach: map each symbol to its value, then traverse the string — if the current numeral is less than the next one, subtract its value; otherwise add it.

import java.util.HashMap;
public class RomanToInteger {
public static int romanToInt(String s) {
HashMap<Character, Integer> romanMap = new HashMap<>();
romanMap.put('I', 1);
romanMap.put('V', 5);
romanMap.put('X', 10);
romanMap.put('L', 50);
romanMap.put('C', 100);
romanMap.put('D', 500);
romanMap.put('M', 1000);
int total = 0;
int length = s.length();
for (int i = 0; i < length; i++) {
int value = romanMap.get(s.charAt(i));
// Check if the next numeral exists and is larger
if (i + 1 < length && romanMap.get(s.charAt(i + 1)) > value) {
total -= value; // Subtract if current is less than next
} else {
total += value; // Add otherwise
}
}
return total;
}
}

Handles all valid Roman numerals in the range [1, 3999]. Time: O(n). Space: O(1) — the map size is fixed regardless of input.