-
Notifications
You must be signed in to change notification settings - Fork 0
/
romanToInt.js
50 lines (44 loc) · 1018 Bytes
/
romanToInt.js
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
42
43
44
45
46
47
48
49
50
/**
* @param {string} s
* @return {number}
*/
var romanToInt = function (s) {
let roms = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000
}
let arr = [...s];
let sum = 0
for (i = 0; i < arr.length; i++) {
let currNum = arr[i];
let nextNum = arr[i + 1];
if (currNum === 'I') {
if (nextNum === 'V' || nextNum === 'X') {
sum += (roms[nextNum] - roms[currNum])
i++;
}
else sum += roms[currNum]
}
else if (currNum === 'X') {
if (nextNum === 'L' || nextNum === 'C') {
sum += (roms[nextNum] - roms[currNum])
i++;
}
else sum += roms[currNum]
}
else if (currNum === 'C') {
if (nextNum === 'D' || nextNum === 'M') {
sum += (roms[nextNum] - roms[currNum])
i++;
}
else sum += roms[currNum]
}
else sum += roms[currNum]
}
return sum;
};