LeetCode Problem 13. Roman to Integer

Problem

LINK LeetCode Problem 13. Roman to Integer

Solution

/**
* @param {string} s
* @return {number}
*/
var romanToInt = function(s) {
if (!s) {
return 0
}
const r2i = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000,
}
const pairs = {
V: "I",
X: "I",
L: "X",
C: "X",
D: "C",
M: "C",
}
let num = r2i[s[0]]
const len = s.length
for(i=1; i<len; i++) {
const currentRoman = s[i]
const previousRoman = s[i-1]
num = num + r2i[currentRoman]
if (pairs[currentRoman] === previousRoman) {
num = num - (2 * r2i[previousRoman])
}
}
return num
};

Explanation

r2i map tells me the value of each roman number to integar

pairs map helps me evaluate the 6 rules mentioned in the problem statement

I then start by assigning the first roman number to my num variable. And then run a simple for loop over the roman string.

For simple roman string like "III" or "VII" we only need one line as below. We simply get integer value of the current roman character and add that integer to the previous sum.

num = num + r2i[currentRoman]

But, for the 6 special rules mentioned in the problem statement we need to decrease the previous roman character added to our sum twice.

Special case example: "IX" or "CM"

Twice because: 1st time because it was already added to the sum and we don't want to do it because its a special case - that is to reset the sum. 2nd time because its a special case and we actually want to subtract that number instead of adding.

Highlights

Runtime: 140 ms, faster than 87.61% of JavaScript online submissions for Roman to Integer.

Memory Usage: 44.7 MB, less than 67.56% of JavaScript online submissions for Roman to Integer.

Disclaimer

This may not be the optimal solution. And that's okay. The purpose here is to practice problem solving and have fun with algorithms. I am constantly learning new optimized solutions for these problems.

Please comment below if you have a better solution. Let's learn algorithms and data structures together.




Try Etsy For Free
Previous: Huge List of Small AdvicesNext: Make Money Online - FREE Training

Share This Post