Method – 4 –
In this approach we will use an external module called roman to convert an integer to roman and vice versa. We need to install it using pip command first. Write the below command in terminal.
!pip install roman
Then we will use two methods , one to convert integer into roman another to convert roman into integer.
Converting Integer to Roman –
For this purpose we will use the toRoman() method of the roman package, it takes the integer value as it’s argument.
Python3
# Importing the package import roman # converting the integer to Roman # and storing it in variable 'r' r = roman.toRoman( 1904 ) # Printing the converted value print (r) |
Output –
MCMIV
Time Complexity – O(1)
Auxiliary Space – O(1)
Converting Roman to Integer –
Here we will convert a roman value to an integer value using fromRoman() method which takes the roman value as an argument, we need to pass that as a string.
Python3
# Importing the module roman import roman # Converting the roman value # into integer and storing # it in variable 'i' i = roman.fromRoman( "MCMIV" ) # Printing the converted value print (i) |
Output –
1904
Time Complexity – O(1)
Auxiliary Space – O(1)
Python program to convert integer to roman
Given an integer, the task is to write a Python program to convert integer to roman.
Examples:
Input: 5 Output: V Input: 9 Output: IX Input: 40 Output: XL Input: 1904 Output: MCMIV
Below table shows the list of Roman symbols including their corresponding integer values also:
Symbols | Values |
---|---|
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 |
Idea is to convert the units, tens, hundreds, and thousands of places of the given number separately. If the digit is 0, then there’s no corresponding Roman numeral symbol. The conversion of digits 4’s and 9’s are a little bit different from other digits because these digits follow subtractive notation.
Algorithm to convert an Integer value to Roman Numeral
Compare given number with base values in the order 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1. The base value that is just smaller or equal to the given number will be the initial base value (largest base value), Divide the number by its largest base value, the corresponding base symbol will be repeated quotient times, the remainder will then become the number for future division and repetitions. The process will be repeated until the number becomes zero.