DEV Community 👩‍💻👨‍💻

stuxnat
stuxnat

Posted on

JavaScript Algorithm: Roman Numeral Converter

Hello! Today I will be writing about how to solve the Roman numeral converter algorithm.

When writing the solution, we have to remember key caveats in the Roman numeral system, like the number 4 being written as 5 minus 1, so IV.

Instead of writing many if statements, we can use a dictionary to solve this problem.

Step 1: Write dictionary.

const dict = {
    1: 'I',
    4: 'IV',
    5: 'V',
    9: 'IX',
    10: 'X',
    40: 'XL',
    50: 'L',
    90: 'XL',
    100: 'C',
    400: 'CD', 
    500: 'D',
    900: 'CM',
    1000: 'M',
}
function toRoman(num) {

}
Enter fullscreen mode Exit fullscreen mode

Step 2. Write an Array of Numbers
Write an array containing the numbers in the dictionary - we will be looping through it. Because we will need to perform some calculations to convert the given number, we will be using subtraction to solve this problem. Starting from the largest value, we will subtract until we no longer can. For this reason, the numbers in the array are written from largest to smallest.

const numbers = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
Enter fullscreen mode Exit fullscreen mode

Step 3. Write a While-Loop
For this, we will set a variable to an empty string because we will want to append the Roman numeral equivalent to the output string.
If the number in the array is greater than num, then we will go to the following number (this is why the array is in reverse numerical order), compare that to num, and append to the output string whenever we were able to calculate a number.

function toRoman(num) {
    let output = '';
    let i = 0;

    while (num > 0) {
        const subtract = numbers[i];
        if (subtract > num) {
            i++;
        } else {
            num -= subtract;
            output += dict[subtract]

        }
    }
    return output
}
Enter fullscreen mode Exit fullscreen mode

Your final code should look like this:

const numbers = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]

const dict = {
    1: 'I',
    4: 'IV',
    5: 'V',
    9: 'IX',
    10: 'X',
    40: 'XL',
    50: 'L',
    90: 'XL',
    100: 'C',
    400: 'CD',
    500: 'D',
    900: 'CM',
    1000: 'M',
}
function toRoman(num) {
    let output = '';
    let i = 0;

    while (num > 0) {
        const subtract = numbers[i];
        if (subtract > num) {
            i++;
        } else {
            num -= subtract;
            output += dict[subtract]

        }
    }
    return output
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.