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.

  1. Create an Object that stores symbols and integer value
  2. Create a variable that points to the first roman index
  3. Loop through the roman symbols starting at the first index
  4. Since we're mostly adding symbol increment the first roman variable to the current roman symbol
  5. 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
  6. Return the first roman that has been incremented

Here a visual solution below

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Creating my first Chrome Extension: Jira sprint report — Part 2

How to use confirm dialogs in a Laravel Nova Tool

How to create an accessible search bar without a label

React Hooks tutorials for beginners-5

Express vs KoA

Create 3D CSS Buttons Which Move As You Mouse Over

Property Descriptor in Javascript

Setting up Nested Routes in a Note-taking App (pt 2)

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Woodelin florveus

Woodelin florveus

More from Medium

WHAT’S IN MY TECH BACKPACK?

Breadth First Search VS. Depth First Search (with Pictures!)

Find All Numbers Disappeared in an Array (space complexity O(n) and O(1)

Attitude towards Performance