Implement a function that takes a Roman numeral as its argument and returns its value as an integer. You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each digit of the number to be encoded separately, starting with the leftmost digit and skipping any 0s. So 1990 is rendered "MCMXC" (1000 = M, 900 = CM, 90 = XC) and 2008 is rendered "MMVIII" (2000 = MM, 8 = VIII). The Roman numeral for 1666, "MDCLXVI", uses each letter in descending order.
Here's a chart to help out:
Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1,000
Example
solution('XXI'); // should return 21
Tests
solution('I')
solution('IV')
solution('MMVIII')
solution('MDCLXVI')
Good luck!
This challenge comes from jhoffner on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!
Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!
Top comments (11)
Not working, due to the fact that you ignored that if a value is smaller than the next one it's substracted not added... check the test case MCMXC it should be 1990 and yours is 2210
haha you re right! thanks. Was in a rush. will fix it
Fun solution in elixir
JS solution
if you are going from back to front, it is a bit easier to "parse".
So this time F# instead of my usual C# posts.
Yes, still learning...
My solution in Haskell:
The lexer function takes care of translating roman numeral tokens into numbers, which can be applied to whole string to get array of the respective integers.
The array of integers is then parsed with a recursive function.
I went with case in lexer, since that notation seemed neater than defining function for each argument case.
Using pattern matching and tail recursion in Elixir:
TypeScript
I did mine using JavaScript, not really a fast algorithm but I think it's readable and allows your pals to understand what's going on.
Hah, there were lots of latin freaks out there in the 60s. Nice, didn't know about it.