If you are simply looking for a solution to convert integers to roman numerals between 0-59 then here is a simple and quickest solution for it.
Solution
Run the code here: https://repl.it/@VinitKhandelwal/0-59-integer-to-roman-javascript
const getRoman = num => {
if (num===0) {
return "";
}
let result = "";
let n = num%10;
let rest = Math.floor(num/10);
if (n === 0) {
getRoman(rest);
} else if (n<4) {
for (let i=0;i<n; i++) {
result = result + "I";
}
} else if (n === 4) {
result = result + "IV";
} else if (n === 5) {
result = result + "V";
} else if (n < 9) {
result = result + "V";
for (let l = 6; l < 9; l++) {
result = result + "I";
}
} else if (n === 9) {
result = result+"IX";
} else {
result = result + "V";
n = n-5;
for (let i=0; i<n; i++) {
result = result+"I";
}
}
if (rest === 0) {
return result;
} else if (rest<4) {
for (let j = 0; j < rest; j++) {
result = "X" + result;
}
} else if (rest === 4) {
result = "XL" + result;
} else {
result = "L" + result;
}
return result;
}
Example Input
console.log(getRoman(1))
console.log(getRoman(50))
console.log(getRoman(59))
console.log(getRoman(0))
console.log(getRoman(42))
console.log(getRoman(23))
console.log(getRoman(29))
console.log(getRoman(34))
Output
I
L
LIX
XLII
XXIII
XXIX
XXXIV
Comments
Post a Comment