Skip to content

Link to Question

EASY

Roman to Integer

Given a roman numeral, convert it to an integer.

Example

Input:

s = "MCMXCIV"

Output:

1994

Explanation:
M = 1000, CM = 900, XC = 90, IV = 4


Constraints

  • 1 ≤ s.length ≤ 15
  • s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M').
  • It is guaranteed that s is a valid roman numeral in the range [1, 3999].

Solution: Hash Map

  • Time Complexity: O(n), where n is the length of the string.
  • Space Complexity: O(1), as the hash map is of constant size.
C++
class Solution {
public:
    int romanToInt(string s) {
        unordered_map<char, int> values = {
            {'I', 1}, {'V', 5}, {'X', 10}, {'L', 50},
            {'C', 100}, {'D', 500}, {'M', 1000}
        };
        int result = 0;
        for (int i = 0; i < s.size(); ++i) {
            if (i + 1 < s.size() && values[s[i]] < values[s[i + 1]])
                result -= values[s[i]];
            else
                result += values[s[i]];
        }
        return result;
    }
};