LeetCode problem #13 — Roman to integer (JavaScript)


In this LeetCode challenge, we’re asked to convert a roman numeral string to its integer equivalent, in a pretty much complete flip to what we were asked to do on the previous challenge.

Solution: Loop with an object (hashmap)

For this super simple solution, we loop through the characters of the provided string, and for each one we check whether that character is worth more or less than the next one (if the next one exists).

If it’s worth less, that means it is a deduction (for example, in the string “IV”, “I” is worth less (1) than “V” (5), so it is a deduction), and so this value is removed from the overall total.

Otherwise, it’s considered an addition, and added to the total:

Note: I used the word hashmap in this solution’s title because that’s what most solutions for this problem use, however hashmaps aren’t available in JavaScript natively (or rather, they are, but they’re just Objects or Maps).



Duncan McArdle

Full-stack software developer from the UK, author of the Aftermath book series, full time tech-nerd.