Convert Roman to Integer in Java
It is a problem frequently asked in interviews of top IT companies like Google, Amazon, TCS, Accenture, etc. By solving the problem, one wants to check the logical ability, critical thinking, and problem-solving skill of the interviewee. So, in this section, we are going to discuss how to convert roman numerals to integers in Java with different approaches and logic. Also, we will create Java programs for the same.
Roman numerals are the symbolic representation of numbers. These are usually used in watch faces, music theory, etc. There are seven letters used to represent roman numerals. The following table represents the roman numerals and corresponding decimal values.
Roman numerals are formed by joining the symbols and adding their respective values. These are usually written in largest to smallest fashion, and from left to right.
However, the roman numeral for the integer 4 is not IIII; instead, it is written as IV. It means that when there is a smaller number placed before a larger number, the values are subtracted; because the 1 is placed before the 5, we can subtract it to get 4.
The same principle applies to the number 9, which is written as IX.
There are six instances where we required subtraction:
Suppose, we have to convert the roman numeral MCMXC to an integer. In order to get the integer value, we will write the corresponding value of each roman numeral and sum up. Therefore, we get:
M=1000, C=100, M=1000, X=10, C=100
CM=1000-100 = 900
XC=100-10 = 90
M=1000, CM=900, XC=90 = 1990
Hence, MCMXC is equivalent to 1990.
Let's see another example.
Consider the roman numeral LVIII.
L=50, V=5, III=8
L+V+III = 50+5+3 = 58
Let's implement the above steps in a Java program.
Java Program to Convert Roman Numerals to Integer in Java
The corresponding Integer value is: 1155
The time and space complexity of the above approach is O(n), where n is the length of the given roman numeral string.
Let's see another solution for the same.
The corresponding Integer value is: 1915
The time complexity of the above approach is O(n), where n is the length of the given roman numeral string and the space complexity is O(1).