×

Converting Roman to Integer Numerals in java

In this article, you will be acknowledged about the process of conversion of roman numbers to integers in java. The most important approaches are discussed and also the implementation of programs that help in converting integers to roman numerals.

It is a question that is regularly asked in job interviews at prestigious IT firms like Google, Amazon, TCS, Accenture, etc. By figuring out the solution, one may assess the interviewee's logical reasoning, critical reasoning, and problem-solving abilities. Therefore, we will explore various methods and logical processes for converting roman numbers to numbers in Java in this part. We will also develop Java apps for the same.

Roman Numerals

Roman numerals are used to represent numbers symbolically. These are typically employed in music theory, watch faces, etc. Roman numerals are represented by seven letters. The roman numbers and related decimal values are shown in the following table.

CharacterRoman Numeral
I1
V5
X10
L50
C100
D500
M1000

Roman numbers possess the fundamental characteristics.

With a few exceptions, it is typically written highest to lowest, left to right (the right character is greater than the left character in this case.). For instance, IV is identical to 4 in roman numerals.

In this situation, we deduct the right character values from the left character value. IV, for instance, will be 5-1=4. IX will also be 10-1=9 in the same way.

Such properties are:

  • Roman numeral I, which stands for "subtract one," can be used before V or X. For instance, 9 is IX (10-1) = 9 and IV (5-1) = 4.
  • L or C may come before the roman number X to indicate a ten-subtraction. XL (50-10) equals 40, for instance, while XC (100-10) equals 90.
  • Before the roman numerals D or M, the letter C stands for the hundredth subtracted. CM (1000-100) = 900 and CD (500-100) = 400, respectively.

Example :

Let's say we need to translate MCMXC from roman number to integer. We will write a corresponding value for each roman number and add them all up to obtain the integer value. As a result, we get:

M=1000, C=100, M=1000, X=10, C=100

M=1000

CM=1000-100 = 900

XC=100-10 = 90

Hence,

M=1000, CM=900, XC=90 = 1990

MCMXC thus represents 1990.

Methodology

  • Perform iterations over each character in the provided Roman number string.
  • The value of the present Roman character should be compared to its correct Roman character.
  • Add the value of the current character to the total variable if it exceeds or is equivalent to the value of such symbol to the right.
  • Subtract the value of the current character from the overall variable if it is lower than the value of such symbol to the right.

Let us understand it with a simple example program

File name: Roman.java

// Roman Numerals to Numbers Conversion in Java
import java.util.*;
public class Roman {
// A Roman symbol's value is returned by this method.
int value(char r)
{
if (r == 'I')
return 1;
if (r == 'V')
return 5;
if (r == 'X')
return 10;
if (r == 'L')
return 50;
if (r == 'C')
return 100;
if (r == 'D')
return 500;
if (r == 'M')
return 1000;
return -1;
}


// determines a given roman numeral's decimal value
int romanToDecimal(String str)
{
// result initialization
int res = 0;


for (int i = 0; i < str.length(); i++) {

int s1 = value(str.charAt(i));
if (i + 1 < str.length()) {
int s2 = value(str.charAt(i + 1));


// comparing the two numbers
if (s1 >= s2) {
// The present symbol's value is higher than or equal to that of the following symbol.
res = res + s1;
}
else {
// Value of the present symbol is smaller than that of the following symbol.
res = res + s2 - s1;
i++;
}
}
else {
res = res + s1;
}
}


return res;
}
public static void main(String args[])
{
Roman ob = new Roman();


// assuming the provided inputs are valid
String str = "MDCL";
System.out.println("Integer form of the given Roman Numeral"
+ " is "
+ ob.romanToDecimal(str));
}
}

Output

Integer form of the given Roman Numeral is 1650

The above method has an O(n) time and space complexity, where n is the size of the supplied roman numeral string.


Related Topics

String to JSON in Java

Nowadays, receiving data in JSON String format rather than XML is quite frequent. Java does not transform JSON String to JSON Object when dealing with JSON String. However, using the...

3 minutes read.

Java program to print matrix in Z form

In this article, you will be acknowledged about what is a matrix along with an example. Also, most importantly, you will learn how to print matrix in Z form. What is...

5 minutes read.

Java List Node

In Java, List Node is the same as the single linked list, which is the collection of nodes. So, we can say, the list nodes are grouped together to get...

8 minutes read.

Java Maven Silicon

Maven is a build automation tool that is mostly used for Java applications. It allows you to manage the build, reporting, and documentation of a project from the central location. Maven provides...

4 minutes read.

Java.net.SocketException

Exception The problem occurred during the execution of the program. If an exception occurs in the program, the program gets terminated. To skip the exception occurring statements, we have to handle...

4 minutes read.

Java String Reader

StreamReaderClass: This class is present in the java.io package. It is a character stream in which string act as a source.This method provides to read characters from a string. Character Stream: This class...

3 minutes read.

Java Interface Keyword

An interface is also known as the blueprint in Java. It has constants of static values and methods of abstraction. The interface is a mechanism used by Java to declare...

3 minutes read.

Process and Thread in Java

Process It is a program that is running on your computer. The process is a heavy-weight, which takes memory separately to other processes. The process may be a small background task like spell-checker; it...

11 minutes read.

Java Code Optimization

We encounter the idea of optimization while working on any Java application. It is essential that the code we write is not only clear and error-free but also optimized, meaning...

9 minutes read.

Java Keywords

Java Keywords The particular words which are used in java programming language that act like a key or important words to write a code are called java keywords. Java Keywords are...

4 minutes read.

Java RandomAccessfile

Writing and reading to random access files are done using this class. An array of many bytes is how a random access file operates. By changing the implied file pointer...

3 minutes read.

Java Boolean compareTo() method

The compareTo() method of Java Boolean class compares the Boolean argument with the Boolean instance and returns integer value, zero, or negative 1, or positive 1 based on the result...

2 minutes read.

How to Convert Integer to String in Java

How to Convert int to String in Java It is used when you want to convert an integer to String. You can convert int to String by using the following methods: Using...

3 minutes read.

Least Operator to Express Number in Java

In this article, we will learn about how to obtain a target number using a single number or a single integer by leveraging least operators in Java. There can be...

3 minutes read.

Java Integer toUnsignedLong() method

The toUnsignedLong() method of Java Integer class returns a long value by simply converting the given argument to long after an unsigned conversion. Syntax public static long toUnsignedLong (int  x) Parameters The parameter ‘x’...

1 minute read.

Different Ways to Take Input from User in Java

Any information provided to a system for use is known as user input. Any responsive software or application must include user input. In Java, there are 4 different ways to...

5 minutes read.

Application of Array in Java

In this article we are going to acknowledge about what the array is, types of arrays and their applications. What is an array? An array is often a set of interrelated elements...

4 minutes read.

Java Network Programming (Socket Programming in Java)

JAVA NETWORK Network programming is used to execute programs across multiple machines that are connected by a network. The java.net package contains a collection of classes and interfaces that provide this...

3 minutes read.

Java Else Keyword

The else statement specifies a section of Java code that will run if an if statement's condition is false.The following conditional statements can be used in Java:To provide a block...

3 minutes read.

How to Convert int to long in Java

How to Convert int to long in Java When two variables of different types are involved in the single expression, Java compiler uses built-in library function to convert the variable to...

2 minutes read.