Here is my slow-poke code, done before class where Ramon showed us how to re-factor the code more efficiently:
function convertToRoman(num) {
if (num <= 0) return ‘error’;
let result = ‘’;
let remaining = num;
if (num >= 1000) {
for (let i = 0; i < Math.floor(num / 1000); i++) {
result += ‘M’;
}
remaining = num % 1000;
}
if (remaining >= 900) {
result += ‘CM’;
remaining -= 900;
}
if (remaining >= 500) {
result += ‘D’;
remaining -= 500;
}
if (remaining >= 400) {
result += ‘CD’;
remaining -= 400;
}
if (remaining >= 100) {
for (let i = 0; i < Math.floor(remaining / 100); i++) {
result += ‘C’;
}
remaining = remaining % 100;
}
if (remaining >= 90) {
result += ‘XC’;
remaining -= 90;
}
if (remaining >= 50) {
result += ‘L’;
remaining -= 50;
}
if (remaining >= 40) {
result += ‘XL’;
remaining -= 40;
}
if (remaining >= 10) {
for (let i = 0; i < Math.floor(remaining / 10); i++) {
result += ‘X’;
}
remaining = remaining % 10;
}
if (remaining >= 9) {
result += ‘IX’;
remaining -= 9;
}
if (remaining >= 5) {
result += ‘V’;
remaining -= 5;
}
if (remaining >= 4) {
result += ‘IV’;
remaining -= 4;
}
if (remaining >= 1) {
for (let i = 0; i < remaining; i++) {
result += ‘I’;
}
remaining = 0;
}
if (remaining != 0) return ‘error’;
return result;
}
convertToRoman(36);
console.log(convertToRoman(1798));