DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 70

The task is to implement a function that converts Roman numerals to integers.

The boilerplate code:

function romanToInteger(str) {
  // your code here
}
Enter fullscreen mode Exit fullscreen mode

The letters representing numbers in the Roman numeral system are seven in number.

const map = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000

}
Enter fullscreen mode Exit fullscreen mode

Roman numerals usually add numbers together (X + V = 15). The only exception being when the next number is bigger than the previous one, i.e IV, IX. In that case, one is subtracted from the bigger number.

for (let i = 0; i < str.length; i++) {
    let curr = map[str[i]];
    let next = map[str[i + 1]];

    if (next > curr) {
      result -= curr;
    } else {
      result += curr;
    }

Enter fullscreen mode Exit fullscreen mode

Curr is the numeral being checked, while next is the number beside it which is checked to see if it is bigger.

The final code:

function romanToInteger(str) {
  // your code here
  const map = {
    I: 1,
    V: 5,
    X: 10,
    L: 50,
    C: 100,
    D: 500,
    M: 1000
  }
  let result = 0;

  for(let i = 0; i < str.length; i++) {
    let curr = map[str[i]];
    let next = map[str[i + 1]];

    if(next > curr) {
      result -= curr;
    } else {
      result += curr;
    }
  }
  return result
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)