This one is similar to the Integer to Roman one, but it has some differences.
Let's begin by creating a map of our values as we will need to be able to reference these later. When we have this map handy, we can reference it when looking at every letting in the string. Here's a few string examples to keep in mind too: XIX, XI which is 19 and 11.
function romanToInteger(string) {
let map = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000,
}
Next we will loop through the string and assign each letter as either current or next.
In XI, or 11, the current is X and the next is I.
If the current letter is greater than the next, we can add it to our result normally.
In the case of XI, we can add 10 and then next, which is 1 and get 11.
If the current letter is less than the next one, as is the case in 20, XIX, we want to subtract the next element by the current element.
So, imagine this. Looking at XIX, current is X and next is I. Since X is greater then I, we add X. Then we look at I and X, the current isn't greater than the next, so we add the values of next minus the current or 10 - 1.
This gets up to 19.
function romanToInteger(string) {
let map = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000,
}
let result = 0
for (let i = 0; i < string.length; i++) {
let current = map[string.charAt(i)]
let next = map[string.charAt(i+1)]
if (current > next) {
result += current
} else {
result += next - current
}
}
}
This should handle most cases except for the last case, which is when we are at the end of the string and there are no more next elements to review.
In this case, we wrap all the if statements under a new if statement, that says as long as there is a next statement, run these if statements.
function romanToInteger(string) {
let map = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000,
}
let result = 0
for (let i = 0; i < string.length; i++) {
let current = map[string.charAt(i)]
let next = map[string.charAt(i+1)]
if (next) {
if (current > next) {
result += current
} else {
result += next - current
}
}
} else {
result += current
}
return result
}
And there we've got it folks.
Top comments (1)
good catch! The second X should be a M for a 1000, that should fix things