The task is to implement a function that converts Roman numerals to integers.
The boilerplate code:
function romanToInteger(str) {
// your code here
}
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
}
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;
}
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
}
That's all folks!
Top comments (0)