Roman to Integer

Easy StringHash Map

Problem

Convert a Roman numeral string (I, V, X, L, C, D, M; subtractive notation IV, IX, XL, XC, CD, CM) to its integer value.

Example 1 Input: "III" Output: 3
Example 2 Input: "IV" Output: 4
Example 3 Input: "LVIII" Output: 58
Example 4 Input: "MCMXCIV" Output: 1994

Constraints

Approach — Hashing & Counting

This is a Hashing & Counting problem. The idea: store what you've seen in a hash map for O(1) lookups, trading a little space to avoid a nested scan. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.

Complexity: O(n) time, O(n) space.

Solution code

Python

class Solution:
    def romanToInt(self, s):
        val = {'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 val[ch] < val[s[i + 1]]:
                total -= val[ch]
            else:
                total += val[ch]
        return total

Java

class Solution {
    public int romanToInt(String s) {
        int total = 0, prev = 0;
        for (int i = s.length() - 1; i >= 0; i--) {
            int v = val(s.charAt(i));
            total += (v < prev) ? -v : v;
            prev = v;
        }
        return total;
    }

    private int val(char c) {
        switch (c) {
            case 'I': return 1;
            case 'V': return 5;
            case 'X': return 10;
            case 'L': return 50;
            case 'C': return 100;
            case 'D': return 500;
            case 'M': return 1000;
            default:  return 0;
        }
    }
}

Practice it

Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.

Solve Roman to Integer interactively → ← All solutions