Answer:
The code is given below in Java with appropriate comments
Explanation:
import java.util.*;
public class RomantoDecimal {
public static void main(String[] args)
{
Scanner SC = new Scanner(System.in);
RomantoDecimal r = new RomantoDecimal();
System.out.println("Enter a Roman number :");
// INPUT A ROMAN NUMBER
String rNum = SC.next();
// CALL convertToDecimal FOR CONVERSION OF ROMAN TO DECIMAL
r.convertToDecimal(rNum);
}
// M=1000, D=500, C=100, L=50, X=10, V=5, I=1
public void convertToDecimal(String roamNo)
{
int number = 0;
// TEACK EACH DIGIT IN THE GIVEN NUMBER IN REVERSE ORDER
for (int i = roamNo.length() - 1; i >= 0; i--)
{
// FIND OUT WHETHER IT IS 'M' OR NOT
if (roamNo.charAt(i) == 'M')
{
if (i != 0)
{ // CHECK WHETHER THERE IS C BEFORE M
if (roamNo.charAt(i - 1) == 'C')
{
number = number + 900;
i--;
continue;
}
}
number = number + 1000;
}
// FIND OUT WHETHER IT IS 'D' OR NOT
else if (roamNo.charAt(i) == 'D')
{
if (i != 0)
{
// CHECK WHETHER THERE IS C BEFORE D
if (roamNo.charAt(i - 1) == 'C')
{
number = number + 400;
i--;
continue;
}
}
number = number + 500;
}
// FIND OUT WHETHER IT IS 'C' OR NOT
else if (roamNo.charAt(i) == 'C')
{
if (i != 0)
{
if (roamNo.charAt(i - 1) == 'X')
{
number = number + 90;
i--;
continue;
}
}
number = number + 100;
}
else if (roamNo.charAt(i) == 'L')
{
if (i != 0)
{
if (roamNo.charAt(i) == 'X')
{
number = number + 40;
i--;
continue;
}
}
number = number + 50;
}
// FIND OUT WHETHER IT IS 'X' OR NOT
else if (roamNo.charAt(i) == 'X')
{
if (i != 0)
{
if (roamNo.charAt(i - 1) == 'I')
{
number = number + 9;
i--;
continue;
}
}
number = number + 10;
}
// FIND OUT WHETHER IT IS 'V' OR NOT
else if (roamNo.charAt(i) == 'V')
{
if (i != 0)
{
if (roamNo.charAt(i - 1) == 'I')
{
number = number + 4;
i--;
continue;
}
}
number = number + 5;
}
else // FIND OUT WHETHER IT IS 'I' OR NOT
{
number = number + 1;
}
}// end for loop
System.out.println("Roman number: " + roamNo + "\nIts Decimal Equivalent: " + number);
}
}