Algorithm Question: Roman to Integer
In this algorithm journey, I was asked to convert roman numerals to integers. The problem started, “Given a roman numeral, convert it to an integer.”. I was caught off guard by this problem because I didn’t know where to start. I looked more closely and at the question and it slowly gave me hints and clues on how to solve the problem. For example, the explanation showed that roman is written from left to right and if the first number is smaller than the next, subtract it.
Initial Implementation
Roman Numerals are represented by symbols that have integer values. Symbols such as I = 1, V = 5, and X = 10. Given these symbols, I would have to find a solution that translates to a whole number. The trick to getting the solution is, if given a symbol such as IV I would need to subtract and return the correct integer. My initial approach was to start storing symbols and values into an object and access them along with my for loop iteration. Below are my steps to solving the problem.
- Create an Object that stores symbols and integer value
- Create a variable that points to the first roman index
- Loop through the roman symbols starting at the first index
- Since we're mostly adding symbol increment the first roman variable to the current roman symbol
- Add a conditional that states: if the current roman is greater than the one before subtracts the first roman by 2 and multiply the roman before it
- Return the first roman that has been incremented
Here a visual solution below