![]() |
VOOZH | about |
Given a Roman numeral, the task is to find its corresponding decimal value.
Example :
Input: IX Output: 9 IX is a Roman symbol which represents 9 Input: XL Output: 40 XL is a Roman symbol which represents 40 Input: MCMIV Output: 1904 M is a thousand, CM is nine hundred and IV is four
Roman numerals are based on the following symbols.
SYMBOL VALUE I 1 IV 4 V 5 IX 9 X 10 XL 40 L 50 XC 90 C 100 CD 400 D 500 CM 900 M 1000
Approach: A number in Roman Numerals is a string of these symbols written in descending order(e.g. M's first, followed by D's, etc.). However, in a few specific cases, to avoid four characters being repeated in succession(such as IIII or XXXX), subtractive notation is often used as follows:
Algorithm to convert Roman Numerals to Integer Number:
Following is the implementation of the above algorithm:
Output:
Integer form of Roman Numeral is 1904
Complexity Analysis:
Approach 2 - In this method, we will convert an integer to roman and back using an external module named roman. First, we must install it using the pip command. In the terminal, type the command below.
!pip install roman
Now after successful installation we will import the module and use the method fromRoman() which takes a Roman value as argument and converts it into decimal and returns it.
Syntax of fromRoman() method -
fromRoman("<roman_value>")
Inside the fromRoman method we need to pass the roman value as string. The value passed must be in uppercase letters.
Implementation -
Output -
1904 55 24
Time Complexity - O(N)
Auxiliary Space - O(1)
Please refer complete article on Converting Roman Numerals to Decimal lying between 1 to 3999 for more details!
METHOD 3:Using re module
APPROACH:
This program takes a Roman Numeral as input and converts it to its equivalent Decimal value using a dictionary that maps the Roman Numerals to their corresponding values.
ALGORITHM:
1.Create a dictionary that maps each Roman Numeral to its corresponding Decimal value.
Initialize the result variable to zero.
2.Loop through the input Roman Numeral string.
3.Check if the value of the current Roman Numeral is greater than the previous Roman Numeral. If so, subtract twice the value of the previous Roman Numeral from the result.
4.Otherwise, add the value of the current Roman Numeral to the result.
5.Print the Decimal equivalent of the given Roman Numeral.
The Decimal equivalent of MCMIV is 1904
Time complexity:
The time complexity of the program is O(n), where n is the length of the input Roman Numeral string. This is because we loop through the string once to calculate the Decimal equivalent.
Auxiliary Space:
The space complexity of the program is O(1), because we only use a constant amount of extra space to store the dictionary and result variable.