LeetCode #13 – Roman to Integer

For a problem labeled ‘Easy’, this one is quite challenging…

However, it is also quite simple if you know certain classes, such as the Map class. Using a HashMap, it is quite easy to assign certain values to certain letters. 

Here is how you initialize them:

As you can see, each roman numeral is assigned a value, and using these values, you can easily get the value. All you need to do is to check each numeral and the one after it and see whether or not you subtract or add from them. Ex(IV = 4 because 5 – 1 = 4, but VI = 6 because 5 + 1 = 6). After that, you add everything up and you get your final value. Here is my final code:

Here is the output:

Here are the logistics of my solution:

While slightly inefficient, it still works. That is all from me for now. I hope you guys at least learned something today, and that you all have a great day!

By:

Posted in:


Leave a comment