Roman to Integer

Updated on 01 July, 2025
Roman to Integer header image

Problem Statement

Roman numerals are represented using seven unique symbols: I, V, X, L, C, D, and M, with each symbol corresponding to specific integer values. These numerals are combined and occasionally subtracted following specific rules to represent numbers. For example, the numeral for '2' is represented as "II", signifying a simple addition of two ones. However, Roman numeral rules adjust for specific instances, such as four being written as "IV" instead of "IIII", which uses subtraction to modify the representation (1 before 5 signifies a subtraction of one from five).

The numerals typically appear from largest to smallest from left to right unless implementing the subtraction rule. The task is to interpret these numeral strings and convert them into their corresponding integer values. The challenge lies in correctly handling both the direct additive relationships as well as the specific subtractive rules embedded within the numeral format.

Examples

Example 1

Input:

s = "III"

Output:

3

Explanation:

III = 3.

Example 2

Input:

s = "LVIII"

Output:

58

Explanation:

L = 50, V= 5, III = 3.

Example 3

Input:

s = "MCMXCIV"

Output:

1994

Explanation:

M = 1000, CM = 900, XC = 90 and 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].

Approach and Intuition

To convert a Roman numeral into its integer form, we should consider two main tasks:

  1. Understand each Roman numeral symbol and its corresponding value.
  2. Recognize when subtraction is used instead of addition.

Process Overview:

  1. Create a map of Roman numerals to their respective values:
    • I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1000
  2. Traverse the string from left to right and convert each symbol to its value.
  3. To handle the subtraction cases, compare each symbol with the next one:
    • If a symbol represents a smaller number than the one that follows (e.g., I before V), subtract the smaller value from the sum instead of adding.
    • Otherwise, simply add the value of the symbol to the total sum.

Detailed Steps:

  1. Initialize a total sum as 0.
  2. Iterate over the string of Roman numerals until the second-to-last character.
    • For each character, check if it and the next character form a subtraction pair (like IV or IX).
    • If a subtraction condition is met, subtract the current value from the total.
    • If not, add the current character's value.
  3. Add the value of the last character to the total (since there's no next character to check for a subtraction condition).

By following these steps, you can correctly interpret any valid Roman numeral string within the provided constraints of length and characters, ensuring an accurate translation to its integer equivalent.

Solutions

  • C++
  • Java
  • C
  • JavaScript
  • Python
cpp
class Solution {
public:
    static unordered_map<char, int> romanValues;
    int convertRomanToInt(string roman) {
        char previousChar = roman[roman.size() - 1];
        int previousValue = romanValues[previousChar];
        int result = previousValue;
    
        for (int index = roman.size() - 2; index >= 0; index--) {
            char currentChar = roman[index];
            int currentValue = romanValues[currentChar];
            if (currentValue < previousValue) {
                result -= currentValue;
            } else {
                result += currentValue;
            }
            previousValue = currentValue;
        }
        return result;
    }
};
    
unordered_map<char, int> Solution::romanValues = {
    {'M', 1000}, {'D', 500}, {'C', 100}, {'L', 50},
    {'X', 10},   {'V', 5},   {'I', 1}};

The provided C++ code defines a solution to convert a Roman numeral string into its integer equivalent. It achieves this using the following method:

  • First, it initializes a static unordered_map to map Roman characters to their corresponding integer values. This map is filled with typical Roman numeral values ('I', 'V', 'X', 'L', 'C', 'D', and 'M') with their integer equivalents.

  • The convertRomanToInt function starts by initializing from the last character of the Roman string, leveraging it to manage the addition and subtraction rules of Roman numerals.

  • To determine the integer value of the Roman string, iterate backward from the second last character to the beginning. For each character:

    • Compare its mapped value against the value of the previous character.
    • If the current value is less than the previous value, subtract it from the result; otherwise, add it.
  • The result computed in the loop is then returned as the output of the function.

This approach effectively handles Roman numeral conversion in a single pass through the string by using a map for constant-time look-up and a simple loop that adjusts the result based on the order of numerals. The use of subtraction for numerals that denote less value appearing before those of higher value, like in "IV" and "IX", is a key component of correctly interpreting Roman numerals.

java
class RomanConverter {
    static Map<String, Integer> romanValues = new HashMap<>();
    
    static {
        romanValues.put("M", 1000);
        romanValues.put("D", 500);
        romanValues.put("C", 100);
        romanValues.put("L", 50);
        romanValues.put("X", 10);
        romanValues.put("V", 5);
        romanValues.put("I", 1);
    }
    
    public int convertToInteger(String roman) {
        String lastRomanChar = roman.substring(roman.length() - 1);
        int valueOfLastRoman = romanValues.get(lastRomanChar);
        int resultantInteger = valueOfLastRoman;
    
        for (int i = roman.length() - 2; i >= 0; i--) {
            String currentRomanChar = roman.substring(i, i + 1);
            int currentValue = romanValues.get(currentRomanChar);
            if (currentValue < valueOfLastRoman) {
                resultantInteger -= currentValue;
            } else {
                resultantInteger += currentValue;
            }
            valueOfLastRoman = currentValue;
        }
        return resultantInteger;
    }
}

This solution provides a method to convert a Roman numeral string to its equivalent integer value using Java. The approach leverages a HashMap to map each Roman numeral character to its respective integer value. The class RomanConverter includes a static initialization block that populates the HashMap with values corresponding to Roman numerals.

The core of the solution is the convertToInteger(String roman) method, which processes each character of the input Roman string from right to left. It starts by initializing the result with the value of the last Roman numeral character. As it iterates backwards through the string, it compares the integer value of the current numeral with the preceding one (moving from right to left in the string):

  • If the current numeral's value is less than the preceding numeral's value, subtract the current numeral's value from the result.
  • If the current numeral's value is equal to or greater than the preceding numeral's value, add it to the result.

This logic correctly handles the specific rules of Roman numeral notation, such as IV being 4 and IX being 9.

Key points of the process:

  • Initialize by reading and storing the value of the last character as it doesn't have a right neighbor to compare with.
  • Move leftward, subtracting the value of numerals that are less than the preceding ones and adding those that are equal or more.

The final calculated value at the end of loop iteration is returned as the resultant integer. This method effectively handles typical formation rules in Roman numerals, converting them accurately to their integer counterparts. Use this approach to easily parse strings of Roman numerals and retrieve their numerical values in applications such as historical data processing or educational tools.

c
struct RomanNumeral {
    char symbol;
    int number;
};
    
const RomanNumeral roman_numerals[] = {
    {'I', 1},   {'V', 5},   {'X', 10},  {'L', 50},
    {'C', 100}, {'D', 500}, {'M', 1000},
};
    
int get_numeral_value(char symbol) {
    for (int idx = 0; idx < sizeof(roman_numerals) / sizeof(roman_numerals[0]); ++idx) {
        if (roman_numerals[idx].symbol == symbol) {
            return roman_numerals[idx].number;
        }
    }
    return 0;
}
    
int romanToInteger(char* roman) {
    int result = get_numeral_value(roman[strlen(roman) - 1]);
    for (int i = strlen(roman) - 2; i >= 0; --i) {
        if (get_numeral_value(roman[i]) < get_numeral_value(roman[i + 1])) {
            result -= get_numeral_value(roman[i]);
        } else {
            result += get_numeral_value(roman[i]);
        }
    }
    return result;
}

The provided C code defines a solution for converting a Roman numeral string into its equivalent integer value.

  • It starts by defining a structured data type RomanNumeral which consists of a char representing the Roman numeral and an int for its corresponding integer value.
  • A constant array roman_numerals initializes these Roman numeral values.
  • The get_numeral_value function iterates through this array to find and return the integer value for a given Roman numeral character. If the character does not match any Roman numeral, the function returns 0.
  • The main function romanToInteger calculates the integer equivalent of the input Roman numeral string by processing the string from right to left. It initializes result with the value of the last Roman character.
  • For each character in the string (from the second last to the first), it compares the value of the current numeral with the next numeral (right to left). If the current numeral's value is less than the next, it subtracts this value from result. Otherwise, it adds the value.
  • Finally, result is returned which represents the integer value of the entire Roman numeral string.

This approach efficiently handles each numeral in direct context of its successor to account for the subtractive combinations often found in Roman numeral representations (like IV for 4 and IX for 9). The use of a fixed array for numeral values ensures quick access and comparison, making the function optimal for conversion tasks within the bounds of standard Roman numerals.

js
var romanToDecimal = function (input) {
    const numeralValues = {
        I: 1,
        V: 5,
        X: 10,
        L: 50,
        C: 100,
        D: 500,
        M: 1000,
    };
    
    let prevValue = input[input.length - 1];
    let sum = numeralValues[prevValue];
        
    for (let index = input.length - 2; index >= 0; index--) {
        let current = input[index];
        let currentValue = numeralValues[current];
        if (currentValue < numeralValues[prevValue]) {
            sum -= currentValue;
        } else {
            sum += currentValue;
        }
        prevValue = current;
    }
    return sum;
};

The provided JavaScript function, romanToDecimal, converts a Roman numeral string into its corresponding integer value. The function operates using the following key steps:

  1. Define an object, numeralValues, to map each Roman numeral character to its integer value.
  2. Initialize prevValue to the last character of the input string and sum to the corresponding integer value of prevValue.
  3. Iterate backwards through the input string, starting from the second-to-last character.
    • For each character, determine its value.
    • If the value is less than the value of prevValue, subtract this value from sum.
    • If the value is equal to or greater than the value of prevValue, add this value to sum.
    • Update prevValue to the current character.
  4. Return the calculated sum, which represents the integer value of the input Roman numeral.

This function effectively handles the conversion by considering the nuances of Roman numeral representation, where the placement of a smaller numeral before a larger numeral indicates subtraction. This approach ensures accurate conversion of a wide range of Roman numerals into their decimal counterparts.

python
roman_values = {
    "I": 1,
    "V": 5,
    "X": 10,
    "L": 50,
    "C": 100,
    "D": 500,
    "M": 1000,
}
    
class RomanConverter:
    def roman_to_integer(self, roman: str) -> int:
        sum_result = roman_values.get(roman[-1])
        for index in reversed(range(len(roman) - 1)):
            if roman_values[roman[index]] < roman_values[roman[index + 1]]:
                sum_result -= roman_values[roman[index]]
            else:
                sum_result += roman_values[roman[index]]
        return sum_result

This solution provides a method to convert a Roman numeral string to its integer value using Python 3. The implementation involves creating a dictionary called roman_values to map each Roman character to its respective integer value. Then, a class named RomanConverter is defined containing a method roman_to_integer.

  • Define a dictionary roman_values that assigns integer values to Roman numeral characters.
  • Create a class RomanConverter.
  • Within the RomanConverter class, define the function roman_to_integer that takes a string roman.
  • Start by retrieving the integer value of the last character of the roman string using the roman_values dictionary.
  • Iterate through the string in reverse order, excluding the last character already evaluated.
  • Compare the integer value of each character with the next character (right to left): subtract it if smaller, otherwise add it to the result.
  • Return the total after parsing all characters.

This method effectively handles conversions by leveraging a dictionary for constant-time lookups and a single pass evaluation from the end of the string to the start, allowing for straightforward and efficient subtraction logic where required by Roman numeral rules.

Comments

No comments yet.