-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathroman_to_integer.js
More file actions
34 lines (32 loc) · 979 Bytes
/
roman_to_integer.js
File metadata and controls
34 lines (32 loc) · 979 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
var romanToInt = function (s) {
// Map to store romans numerals
const romanMap = new Map();
// Fill the map
romanMap.set('I', 1);
romanMap.set('V', 5);
romanMap.set('X', 10);
romanMap.set('L', 50);
romanMap.set('C', 100);
romanMap.set('D', 500);
romanMap.set('M', 1000);
// Length of the given string
const n = s.length;
// Variable to store result
let num = romanMap.get(s[n - 1]);
// Loop for each character from right to left
for (let i = n - 2; i >= 0; i--) {
// Check if the character at right of current character is
// bigger or smaller
if (romanMap.get(s[i]) >= romanMap.get(s[i + 1])) {
num += romanMap.get(s[i]);
} else {
num -= romanMap.get(s[i]);
}
}
return num;
};
console.log(romanToInt("III"));
console.log(romanToInt("IV"));
console.log(romanToInt("IX"));
console.log(romanToInt("LVIII"));
console.log(romanToInt("MCMXCIV"));