Decimal to roman numeral converter in java
Java program for Decimal to roman numeral converter. Here more solutions.
/*
Java program for
Conversion from Decimal to roman number
*/
public class Perform
{
// Display roman value of n
public static void result(int n)
{
switch (n)
{
// Test Cases
case 1:
System.out.print("I");
break;
case 4:
System.out.print("IV");
break;
case 5:
System.out.print("V");
break;
case 9:
System.out.print("IX");
break;
case 10:
System.out.print("X");
break;
case 40:
System.out.print("XL");
break;
case 50:
System.out.print("L");
break;
case 90:
System.out.print("XC");
break;
case 100:
System.out.print("C");
break;
case 400:
System.out.print("CD");
break;
case 500:
System.out.print("D");
break;
case 900:
System.out.print("DM");
break;
case 1000:
System.out.print("M");
break;
}
}
public static long select(long number, int[] collection, int size)
{
int n = 1, i = 0;
for (i = 0; i < size; ++i)
{
if (number >= collection[i])
{
n = collection[i];
}
else
{
break;
}
}
result(n);
// Reduce the value of number
return number - n;
}
public static void romanNo(long number)
{
if (number <= 0)
{
// When is not a natural number
return;
}
// Base case collection
int[] collection = {
1,
4,
5,
9,
10,
40,
50,
90,
100,
400,
500,
900,
1000
};
// Get the size of collection
int size = collection.length;
System.out.print(" " + number + " : ");
while (number > 0)
{
number = select(number, collection, size);
}
// Add new line
System.out.println();
}
public static void main(String[] args)
{
// Test Case
romanNo(10);
romanNo(18);
romanNo(189);
romanNo(604);
romanNo(982);
romanNo(3000);
}
}
Output
10 : X
18 : XVIII
189 : CLXXXIX
604 : DCIV
982 : DMLXXXII
3000 : MMM
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment