-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathroman-to-integer.js
More file actions
41 lines (29 loc) · 860 Bytes
/
roman-to-integer.js
File metadata and controls
41 lines (29 loc) · 860 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
* @param {string} s
* @return {number}
*/
var romanToInt = function (s) {
const numerals = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000,
};
const strLen = s.length;
let total = 0;
// Loop through the letters
for (let i = 0; i < strLen; i++) {
// Check if the current letter is followed by one with a higher value (indicating a deduction)
if (i < strLen - 1 && numerals[s[i + 1]] > numerals[s[i]]) {
// Remove the current letter's numeric value from the total
total -= numerals[s[i]];
} else {
// Add the current letter's numeric value to the total
total += numerals[s[i]];
}
}
return total;
};