Question: please finish the code below, so when you to enter the number then it will be convert to the Roman number. please note: Roman number
please finish the code below, so when you to enter the number then it will be convert to the Roman number.
please note: Roman number is between 1 and 3999
// Java Program for above approach
class Main
{
// Function to calculate roman equivalent
static String convertToRoman(int num)
{
// storing roman values of digits from 0-9
// when placed at different places
String M[] = {"", "M", "MM", "MMM"};
String C[] = {"", "C", "CC", "CCC", "CD", "D",
"DC", "DCC", "DCCC", "CM"};
String X[] = {"", "X", "XX", "XXX", "XL", "L",
"LX", "LXX", "LXXX", "XC"};
String I[] = {"", "I", "II", "III", "IV", "V",
"VI", "VII", "VIII", "IX"};
// Converting to roman
if (num < 1 || num > 3_999) {
throw new IllegalArgumentException("Invalid input number: " + num);}
String thousands = M[num/1000];
String hundereds = C[(num%1000)/100];
String tens = X[(num%100)/10];
String ones = I[num%10];
String ans = thousands + hundereds + tens + ones;
return ans;
}
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
