You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
🔥 Integer to Roman 🔥 || 5 Solutions || Simple Fast and Easy || with Explanation
Solution - 1
classSolution {
StringintToRoman(intnum) {
//first we create a table of roman word and their values..List<String> romanWord = [
"I",
"IV",
"V",
"IX",
"X",
"XL",
"L",
"XC",
"C",
"CD",
"D",
"CM",
"M"
];
List<int> value = [1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000];
//initialize and set the index i...int i = romanWord.length -1;
//create the solution which will be in string format...String sol ="";
//a loop will be made to begin the procedure...while (num>0) {
//this loop is working until the the value of integer is less or equal to num...while (value[i] <=num) {
//Append the roman numeral into an solution string...
sol += romanWord[i];
//subtract the integral value from the given integer...//Subtract the current number until the given integer is greater than the current number.num-= value[i];
}
i--;
}
//Once we are done with all the roman numerals, we return the solution.return sol;
}
}
Solution - 2
classSolution {
StringintToRoman(intnum) {
List<int> number = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
List<String> roman = [
"M",
"CM",
"D",
"CD",
"C",
"XC",
"L",
"XL",
"X",
"IX",
"V",
"IV",
"I"
];
String res ="";
for (int i =0; i <= number.length -1; i++) {
if (num/ number[i] >=1) {
res += roman[i] * (num~/ number[i]);
num=num- (num~/ number[i]) * number[i];
}
if (num==0) break;
}
return res;
}
}
Solution - 3
classC {
StringintToRoman(intnum) {
String romanNumeral ="";
while (num>=1000) {
romanNumeral +="M";
num-=1000;
}
while (num>=900) {
romanNumeral +="CM";
num-=900;
}
while (num>=500) {
romanNumeral +="D";
num-=500;
}
while (num>=400) {
romanNumeral +="CD";
num-=400;
}
while (num>=100) {
romanNumeral +="C";
num-=100;
}
while (num>=90) {
romanNumeral +="XC";
num-=90;
}
while (num>=50) {
romanNumeral +="L";
num-=50;
}
while (num>=40) {
romanNumeral +="XL";
num-=40;
}
while (num>=10) {
romanNumeral +="X";
num-=10;
}
while (num>=9) {
romanNumeral +="IX";
num-=9;
}
while (num>=5) {
romanNumeral +="V";
num-=5;
}
while (num>=4) {
romanNumeral +="IV";
num-=4;
}
while (num>=1) {
romanNumeral +="I";
num-=1;
}
return romanNumeral;
}
}