LeetCode problem #12 — Integer to Roman Numerals(JavaScript)
In this LeetCode challenge, we’re asked to create a function that will take an integer, and convert it to its roman numeral equivalent.
For all of the below solutions, we’re required to create an array of potential numerals. But what’s interesting is that one requires only the traditional numerals (I, V, X, L, C, D & M), whilst another also requires doubles (CM, CD, XC, etc.), and the last requires all combinations (M, MM, MMM, C, CC, CCC, CD, D, DC, DCC, DCCC, CM, etc.).
There is very little difference in terms of the performance for all 3 (at least using JavaScript).
Solution 1: If statements (recursive)
Ugly at first, I know, but this solution is borderline elegant in its readability. We take a number, match it to and return the highest available roman numeral, and then append the result of calling the whole process again on what remains (AKA we run the function recursively until we’re done):
Solution #2: Looping
This suggestion came from LeetCode user kkang, and uses separate arrays to track numerals and their respective values.
What this solution does is to run until the input number has reached 0. For each iteration, it loops through the available numeral values, finds the biggest one applicable to the outstanding number, stores the corresponding numeral into a global string, and then removes the numeral’s value from the outstanding number. It’s actually pretty similar to solution #1, but without the if statements and recursion:
Solution #3: Math
This incredibly concise solution comes from LeetCode user fabrizio3, and uses just a little bit of math to get the job done.
The way it works is that it first initialises every combination of letters for each level of numeral (1, 10, 100, 1,000) in an array which starts with an empty value. Then, it calculates which array element to apply based on the modulo and / or division of the overall number by the relevant level (the exact path differs by level). The inclusion of the empty first element handles cases where the number is lower than that level (such as 500 being lower than the 1,000 level)
I’d say it’s a little less readable than the others, but it’s certainly elegant: