DEV Community

Cover image for Roman Numeral Converter
Fernando B πŸš€
Fernando B πŸš€

Posted on

Roman Numeral Converter

Who doesn't like roman numerals, am I right? Have you ever been stuck in a place with roman numeral clocks? This is a nice programming challenge that involves using lists or arrays to store the letters/values. You could also use a switch or a literal object.

The conversion is actually quite easy once you understand the algorithm.

The secret sauce here are two arrays, you can do it with one and use objects. The secret is to add 1, 4, 5, 9 combinations from 1 to 1000, numbers after 4000 in roman numerals are not that common, so this is focusing only on 1 through 3,999. Either way this is how they look:

const nums = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
const romanLetters = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"];
Enter fullscreen mode Exit fullscreen mode

Let's take 48 for example.

  1. Iterate through nums until you find a number that 48 is divisable by. i.e. 48 / 40 = 1.2, so this corresponds to index 7 = XL. We only care about Math.Floor(1.2) = 1, 1 is how many times we loop

  2. Inside our loop:

    • Append the value of index 7 to romanNum string = XL
    • Subtract 40 from 48 which give us 8
  3. Repeat steps until the previous subtraction result is 1

Because the way nums is setup, the division result will always be 0-3 and that's great because roman numerals can only be used three times in a row.

I will finish just so you see how it would work. The above steps are the core of the algorithm.

  1. Find what can divide 8, in this case 5. 8/5 = 1.6, or better yet 1. This is index 10 = V.
  2. We loop one time
    • Append the value of index 10 to romanNum string = XLV
    • Subtract 5 from 8 which give us 3

Last round we're almost there:

  1. 3 is divisable by 1, 3/1 = 3, index = 12 = I
  2. We loop 3 times
    • Append the value of index 12 to romanNum string = XLVI
    • Subtract 1 from 3 which give us 2
    • Go back to step 2 until we get to 1, and in the end romanNum string will look like this XLVIII. Don't take my word try it below!

I hope you enjoyed this programming challenge, let me know how you would have done it, or optimized it. Thanks for reading!

Top comments (0)