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

How to use Bootstrap 5 with CDN in Nextjs?

How to use Bootstrap 5 with CDN in Nextjs By Rajdeep Singh

How to build an Augmented Reality XR App with Unity and ARCore to create Augmented Images

How to participate in stake on the moonbeam test net # with tutorial #junjunjun888888#24

Everything You Need to Know About React Portals


Implementing Role-Based Access Control in a Node.js application

Laravel Multi Auth using Guards with Example [Web Authentication]

How to build a website from scratch in 2020

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

K-th Smallest Element in a BST

Binary search and big O notation

Sliding Window Algorithm

How Many Threads is Too Many?