Coding Challenge Practice - Question 79
Source: Dev.to
Problem Description
The task is to implement a function that converts integers to Roman numerals.
Approach
Roman numerals are built from largest to smallest. Specific numbers are represented by symbols; a combination is used to form other numbers.
const values = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
const symbols = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"];
To convert a number, keep subtracting the biggest possible values from the number. Each subtraction adds the corresponding Roman symbol to the result:
for (let i = 0; i = values[i]) {
result += symbols[i];
num -= values[i];
}
The result is a combination of all the symbols after the subtraction is completed.
Final Implementation
function integerToRoman(num) {
const values = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
const symbols = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"];
let result = "";
for (let i = 0; i = values[i]) {
result += symbols[i];
num -= values[i];
}
}
return result;
}
That’s all folks!