LeetCode -[Roman to Integer] JS variations

codeonjim

CodeOnJIm

Posted on September 5, 2022

LeetCode -[Roman to Integer] JS variations

This is one of the lit LeetCode problems that is supposedly "easy". This is certainly not easy but "beginner friendly" after a few trials and errors, (This is where you will shine if you keep at it!). I won't get into the whole description of the problem, rather start discussing this right away assuming you know why you are here. In case you do not know about this problem, here is the problem.

So, since you know that roman integers are counted with few English letters. They are I, V, X, L, C, D, M and each of them has associated numeric value. the very first thing I'm gonna do is to store these values in an object.

const romanD = {
          I: 1,
          V: 5,
          X: 10,
          L: 50,
          C: 100,
          D: 500,
          M: 1000,
    };
Enter fullscreen mode Exit fullscreen mode

Now the thing is, there will be random input (strings) coming in as roman symbols. We have to sum them up. For instance, if the input is 'III' the sum will be 3, since I has a numeric value of 1. So, 'XV' would be 15 and so on. Only difference is, if ANY of the input value has less value than the next one, that would be subtraction, not addition. For instance,
XL === 40 but not 60.

The very first thing I do is pseudo-code. Thanks to CS50!

//store the roman value {}

//split the input

//have an accumulator variable

//run a loop over

//if the curInput < nextInput (substract) else (sum up)

//return or console.log the accumulator
Enter fullscreen mode Exit fullscreen mode

Now the first code is with a traditional ForLoop. Goes like this -

With Traditional forLoop

Ok, In case, this too abstracted for you, here is the simplified version -

simplified version of the for loop

hope this is pretty self-explanatory for you. In case not, leave me a comment I will break down the issue for you.

Now, another variation with ForEach loop now. Goes like this -

With ForEach looop

In case this is abstract again, look at the simplified version up there. It's just the if..else statement that you know. notice that we were able to run a forEach here since we split() the input, which gives us an array. Ya, I know, I haven't mentioned them. Here is the full blown code ...

FullCode

With a forLoop, the execution time is between - 78 to 102ms.
with a forEach, the execution time is between - 74 to 100ms.

Although, your machine's hardware quality impacts this time as well.

💖 💪 🙅 🚩
codeonjim
CodeOnJIm

Posted on September 5, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related