Roman Numeral to Integer

Joseph K Abe
2 min readOct 15, 2021

Continuing my algorithm practice I ran into a pretty fun and challenging problem. The task is to make a function that takes a roman numeral and returns the value of the numeral as an integer. For example “XL” = 40, “V” = 5, “IV” = 4, and so on.

The first step I took was to create a values object were the key is the numeral and the value is the integer that it represents

let values = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000
}

Next was to make an array of all the letters that are used in roman numerals.

let arr = ['I','V','X','L','C','D','M']

Now we have can use this array to to find the values of our numerals!

The tricky thing about roman numerals is that where there is a letter that is less than the following letter you subtract the value from the following letter. For example “IV” = 4. Knowing this we sadly can’t just simply add all the letters up and return the integer value; we will have to keep track of the previous letter to know if it needs to be subtracted or added. Basicly if the previous letter is less than the following it will need to be subtracted instead of added. So I made a let called answer (to keep track of the final answer) and a let called previous (to keep track of the previous letter) and set them both to equal 0.

let answer = 0
let previous = 0

Now that everything is set up its time to make our for loop

for(let i = numeral.length - 1; i >= 0; i--){if(arr.indexOf(numeral[i]) >= previous){answer = answer + values[numeral[i]]}else{answer = answer - values[numeral[i]]}previous = arr.indexOf(numeral[i])}

As you can see I started from the back of the numeral by making i = numeral.length -1 and if i is greater than or equal to 0; i -= 1. The if statement is checking if the letter is greater than or equal to the previous letter then add the values together. If they it is not greater than or equal to the previous then subtract. Our let previous will constantly over write each time it loops for a comparison. This worked perfectly!

Now all there is left to do is return answer. Here is my final solution

function numeralToInteger(numeral) {let arr = ['I','V','X','L','C','D','M'];let values = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000
}
let answer = 0let previous = 0for(let i = numeral.length - 1; i >= 0; i--){
if(arr.indexOf(numeral[i]) >= previous){
answer = answer + values[numeral[i]]
}else{
answer = answer - values[numeral[i]]
}
previous = arr.indexOf(numeral[i])
}
return answer
}

This was one of the more rewarding algorithms that I have solved. Tackling this problem helped me re solidify my OOP skills. “I have to admit its getting better, a little better all the time”!

--

--