Convert Roman Number to Integer

Difficulty: Easy, Asked-in: Amazon, Microsoft, Facebook

Key takeaway: An excellent problem to learn problem-solving using loop.

Let’s understand the problem

Given a Roman numeral, write a program to find its corresponding decimal value. Roman numerals are represented by seven different symbols:

Symbol       Value
I             1
V             5
X             10
L             50
C             100
D             500
M             1000

Problem Note

  • The input contains only the characters 'I', 'V', 'X', 'L', 'C', 'D', 'M'.
  • Input is a valid roman numeral in the range [1, 3999].
  • A number in Roman numerals is a string of these symbols written in descending order i.e. largest to smallest from left to right. For example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII, which is simply X + II. The number 27 is XXVII, which is XX + V + II.
  • We avoid four characters being repeated in successions such as IIII or VIIII. Instead, the number four is written as IV because the 1 is before the 5, and we subtract it making 4. The same principle applies to number 9, which is written as IX. The idea is: when there is a smaller number placed before a larger number, the values are subtracted.

Example 1: Input: XL, Output: 40

Explanation: XL is a Roman symbol which represents 40

Example 2: Input: MCMIV, Output: 1904

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

Example 3: Input: LVIII, Output: 58

Explanation: L = 50, V= 5, III = 3

Example 4: Input: MCMXCIV, Output: 1994

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

Solution using a single loop

Solution idea and steps

According to the properties of Roman numerals, two cases can occur when:

  • Case 1: The symbols appear in descending order, or the same symbol is repeated consecutively.
  • Case 2: A smaller Roman numeral appears before a larger one, forming a subtractive pair.

One solution is to scan the input string and calculate the integer value based on these cases.

Step 1: Declare the variable output to store the integer value of the Roman numeral.

Step 2: Scan the input string using a loop. Inside the loop, declare two variables, curr and next, to store the integer values of the Roman characters at indices i and i + 1. Use the helper function integerValue(char c) to get the integer value of a Roman character.

  • If curr >= next: This is Case 1. Add curr to output: output = output + curr.
  • If curr < next: This is Case 2. Add next - curr to output: output = output + (next - curr). This difference is the combined value of the two Roman characters, so increment i by 1 to skip the next character. Note that i is also incremented by the loop.
  • Boundary condition: Before calculating next, check whether i is at the last index. If it is, there is no next character, so add curr to output: output = output + curr.

Step 3: At the end of the loop, return the value stored in output.

Solution pseudocode

integerValue(c)
    if c is 'I'
        return 1
    if c is 'V'
        return 5
    if c is 'X'
        return 10
    if c is 'L'
        return 50
    if c is 'C'
        return 100
    if c is 'D'
        return 500
    if c is 'M'
        return 1000

    return -1


romanToInteger(S, n)
    output = 0

    for i from 0 to n - 1
        curr = integerValue(S[i])

        if i + 1 < n
            next = integerValue(S[i + 1])

            if curr >= next
                output = output + curr
            else
                // Combine a subtractive pair, such as IV or IX
                output = output + next - curr
                i = i + 1
        else
            // Add the value of the final symbol
            output = output + curr

    return output

Another solution idea similar to the above approach

From the Roman string of a number, we can observe one thing: there is only one smaller number before a larger number. So another basic idea would be:

  • Access each roman character using a loop and check the current character is less than the next character or not. If yes, then we subtract the integer value of the current character from the overall output.
  • Otherwise, we add the integer value of the current character from the overall output. This would be the scenario when string symbols will appear in descending order or three characters being repeated in successions.
  • We need to take care of the boundary condition when we reach the last character.

Solution pseudocode

integerValue(c)
    if c is 'I'
        return 1
    if c is 'V'
        return 5
    if c is 'X'
        return 10
    if c is 'L'
        return 50
    if c is 'C'
        return 100
    if c is 'D'
        return 500
    if c is 'M'
        return 1000

    return -1


romanToInteger(S, n)
    output = 0

    for i from 0 to n - 1
        curr = integerValue(S[i])

        if i + 1 < n
            next = integerValue(S[i + 1])

            if curr >= next
                output = output + curr
            else
                output = output - curr
        else
            output = output + curr

    return output

Solution analysis

In both approaches, we are running a single loop and doing O(1) operations at each iteration. So time complexity = n * O(1) = O(n). We are using a constant number of variables, so space complexity = O(1).

Critical ideas to think!

  • Can we solve this problem using some other approach?
  • Can we think to optimize the above code further?
  • Can we think about solving this problem recursively?
  • Instead of using the helper function integerValue(char c), can we implement the above solution using switch statements or an unordered map?
  • Which solution will perform less number of operations?

Suggested problems to practice

  • Convert integer to English words
  • Convert a decimal number to Roman numerals
  • Validate Roman numerals using regular expression
  • Find the largest roman numeral possible by rearranging characters of a string

Enjoy learning, Enjoy algorithms!

Visualization Lab

See how algorithmic problem solving approaches work and follow each step at your own pace.

Explore Visualisation Lab

Courses and Blogs