×

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

JDBC Architecture

JDBC: JDBC stands for Java Database Connectivity. Sun Microsystems has a specification called JDBC. JDBC is a Java API (Application Programming Interface) that enables users to interact or communicate with...

4 minutes read.

Difference Between Java and PHP

The two most used programming languages are PHP and Java. Both of them have a lot of similarities and distinctions. Let's first grasp each of them individually before examining their...

3 minutes read.

Jdoodle Java

Everything is instantaneous and fast-paced in the modern world. Online compilers available via the internet are immensely helpful for programmers seeking to learn a new programming language but lacking the...

4 minutes read.

Java Exception Propagation

Java Exception Propagation When an exception is being thrown from the peak of the stack and not getting caught, it runs down the stack to the previous method, which is sitting...

3 minutes read.

How to Calculate the Time Difference between Two Dates in Java?

The date is used extensively in Java to calculate date discrepancies. The date of joining an organization, admittance, appointment, etc., can be included when creating the application. The differences between...

4 minutes read.

Java Primitive Data Types

Primitive data types are the simplest data types in a programming language. They’re predefined in the language. The names of the primitive types are quite descriptive of the values that...

2 minutes read.

Java Solid Principles

Java implements the object-oriented SOLID principles for the design of software architecture. Solid Principles Java implements the object-oriented SOLID principles for the design of software architecture.   Five guiding principles transformed...

4 minutes read.

Association in Java

In Java, association refers to the link between two classes established by their objects. One-to-one, one-to-many, and many-to-many connections are managed via association. The Association defines the multiplicity between objects...

5 minutes read.

Java Do While Loop

When we wish to test the exit condition at the end of the loop, we use a do-while loop. The do-while loop always executes its body at least once, because...

1 minute 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.

Print Pencil Shape Pattern in Java

Another pattern made from asterisk symbols that use loops and other logical concepts is the pencil pattern. It is usually requested to draw a pattern using a program. To write the...

6 minutes read.

Java Command not found

Java Command not found error is displayed if Java is not installed on the computer or if the command prompt cannot find Java.exe to run the program. Our Java software...

3 minutes read.

Sorting a String in Java

Sorting a String in Java Sorting is a process of arranging available data objects in a meaningful format that is ascending or descending order. Sorting a string or array of String...

4 minutes read.

What is String in Java?

What is String in Java? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a Java...

4 minutes read.

Knapsack problem in Java

We have a collection of items in the knapsack problem. Every object has a weight and a value. These things should go in a knapsack. But there is a weight...

3 minutes read.

Java String toUpperCase() methods

Java String toUpperCase() method is used to convert all the characters of the String into upper case. Syntax public String toUpperCase() public String toUpperCase(Locale locale) Returns It returns upper case String. Java String toUpperCase() Example 1: public...

1 minute read.

Diamond problem in Java

The Diamond Problem in Java is connected to multiple inheritances. It is also referred to as the "deadly diamond dilemma" or even the "deadly diamond of death”. The solution for...

5 minutes read.

Morris Traversal for Inorder in Java

Through Morris’s traversal, a tree is traversed without the aid of recursion or stacks. Based on the threaded binary tree, the Morris traversal is used. We perform internal modification throughout...

4 minutes read.

Buffer reader to read string in Java

The Buffered Reader class of Java is used to read the stream of characters from the input stream. Program to read string using Buffer reader import java.io.*; class  Demo {   public static void main(String...

3 minutes read.

Short Circuit Logical Operators in Java

When there are two or more relational expressions in a decision-making statement, logical operators are utilized to combine them. The logical operators short circuit and not-short circuit fall into two...

5 minutes read.