Objective: Given a Roman number, write a program to convert it to Integer.

Roman Number –   Letters used in Roman numerals and the corresponding numerical values are given in the table below.

Rules: 

Roman numerals are usually written in highest to lowest from left to right except for some special cases where left character is less than the right character. for example ‘IV’ is equivalent to 4 not ‘IIII’. In such cases, subtract the left character value from the right character value. ‘IV’ will be 5-1 = 4, same for ‘IX’ = 10-1 = 9. Below are the cases –

  • I can be placed before V or X, represents subtract one, so IV (5-1) = 4 and 9 is IX (10-1)=9.

  • X can be placed before L or C represents subtract ten, so XL (50-10) = 40 and XC (100-10)=90.

  • C placed before D or M represents subtract hundred, so CD (500-100)=400 and CM (1000-100)=900.

Example:

Roman: XXV
Integer: 25
---------------------------------------------------
Roman: XXXVI
Integer: 36
---------------------------------------------------
Roman: MXXIII
Integer: 1023
---------------------------------------------------
Roman: DXLII
Integer: 542

Approach:

  • Iterate through given roman number from right to left (reverse).

  • Initialize result = 0.

  • Take one character at a time and check its corresponding numeral from the table and add it to the result. 

  • The only special case that needs to be considered is when the character at left has smaller value than the character at right. for example ‘IX’ for 9 or ‘IV’ for 4, in such cases subtract left character value from the result. Except for this special case, In all other cases, all the pairs have left character value >= right character value.

Attachments: