Press "Enter" to skip to content

How to Convert a Roman Number to Integer

Ajk 0

This question came to my attention from one of my readers a few days ago. They had been asked this question in an online interview and implied that it was quite hard to solve. He had tried converting a Roman Number to Integer, but had ended up in a non-pleasing solution. Well, well, like most readers when I first saw this, I thought to myself… easy! My brain can compute this in half a second so why wouldn’t a computer be able to! As I went on and on in my solution I found out that converting a roman number to integer in java, was not as straight-forward.

I have been insanely busy lately so I will try to be concise and to the point. We need to go through each character of the roman number (assumed to be represented in a String) and add up the values. Easy no? Not exactly… We have forgotten a few points.

  • We can have numerals that denote negative value. For example in ‘IV’ the ‘I’ denotes -1.
  • We may have invalid numbers! XLI is valid, but XXLI and XMI are not!

Following this I implemented a small system to keep track of all roman numerals (I, V, X, L, C, D, M) in an array.
You can see that all numerals which start in 5 have an odd index. All that start with 1 have an even index. Keeping in mind that only the numerals that start with 1 can be put in front of bigger numerals to denote negative value (i.e. IX is -1 + 10), we create the below Java code, which as always can be found on GitHub (under the String library).

Converting a roman number to integer – first and last try

Note that a really good thing about our code is that it’s extensible! If the might Roman Empire came back to power and they decided to continue their numeric system with more characters, our code would be ready to accept them. We would just have to edit our basic char array and we’d be ready to go to translate the Romans with our formidable computer technology which would be able to convert Roman numbers to Integers :)!
As you can see running our roman number to integer – if the code is invalid we return -1, – otherwise we return the converted number.

All things considered as I double check the code I notice that there is a small bug… Can you find it?
As always, hope you guys enjoyed it… and I’ll see you guys next time! ;D

The following two tabs change content below.
If you like one of my posts the best way to support is give it a thumbs up, comment, or share it on social media 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *