This post will discuss how to convert a Roman numeral to the corresponding integer in C++, Java, and Python. Assume valid Roman numeral as input.

The Roman numerals system uses seven different symbols to represent numbers. These are I, V, X, L, C, D, and M, standing for 1, 5, 10, 50, 100, 500, and 1000, respectively. The Roman numerals are in the range [1, 3999], the minimum Roman numeral being I and the maximum Roman numeral being MMMCMXCIX.

 
For example,

Input: VII
Output: 7
Explanation: V = 5, I = 1
 
Input: XXIX
Output: 29
Explanation: X = 10, I = 1
 
Input: CLX
Output: 160
Explanation: C = 100, L = 50, X = 10

The idea is very simple: evaluate the Roman numeral from left to right, keeping a simple rule in mind: when a digit is placed before another digit of higher value, we add the difference between the digits to the result. For example, consider a Roman numeral LXLVI, where the corresponding integer values are L = 50, X = 10, V = 5, I = 1. It can be evaluated as follows:

LXLVI = L + (L – X) + V + I
      = 50 + (50 – 10) + 5 + 1
      = 50 + 40 + 5 + 1
      = 96

It should be noted that putting a lower-valued X before a higher-valued L produces (L - X). Following is the C++, Java, and Python implementation based on the idea:

C++


Download  Run Code

Output:

29

Java


Download  Run Code

Output:

29

Python


Download  Run Code

Output:

29

The time complexity of the above solution is O(n), where n is the length of the Roman string literal.