DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 79

The task is to implement a function that converts integers to Roman numerals.

The boilerplate code

function integerToRoman(num) {
  // your code here
}
Enter fullscreen mode Exit fullscreen mode

Roman numerals are built from largest to smallest. Specific numbers are represented by symbols, in which 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", "XM", "D", "XD", "C", "XC", "L", "XL", "IX", "V", "IV", "I"];

Enter fullscreen mode Exit fullscreen mode

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.length; i++) {
    while (num >= values[i]) {
      result += symbols[i];
      num -= values[i];
    }
  }
Enter fullscreen mode Exit fullscreen mode

The result is a combination of all the symbols after the subtraction is completed.

The final code

function integerToRoman(num) {
  // your code here      
  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.length; i++) {
    while(num >= values[i]) {
      result += symbols[i];
      num -= values[i];
    }
  }
  return result;
}

Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)