forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0013-roman-to-integer.js
65 lines (59 loc) · 1.57 KB
/
0013-roman-to-integer.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/**
* @param {string} s
* @return {number}
*/
var romanToInt = function (s) {
let romans = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000,
};
let arr = s.split('');
let sum = 0;
for (let i = arr.length - 1; i >= 0; i--) {
// IV : 4
if (romans[arr[i]] === romans['V']) {
if (romans[arr[i - 1]] === romans['I']) {
sum -= 1 * 2;
}
}
// IX : 4
if (romans[arr[i]] === romans['X']) {
if (romans[arr[i - 1]] === romans['I']) {
sum -= 1 * 2;
}
}
// XL : 40
if (romans[arr[i]] === romans['L']) {
if (romans[arr[i - 1]] === romans['X']) {
sum -= 10 * 2;
}
}
// XC : 90
if (romans[arr[i]] === romans['C']) {
if (romans[arr[i - 1]] === romans['X']) {
sum -= 10 * 2;
}
}
// CD : 400
if (romans[arr[i]] === romans['D']) {
if (romans[arr[i - 1]] === romans['C']) {
sum -= 100 * 2;
}
}
// CM : 900
if (romans[arr[i]] === romans['M']) {
if (romans[arr[i - 1]] === romans['C']) {
sum -= 100 * 2;
}
}
sum += romans[arr[i]];
}
return sum;
};
// Runtime: 148 ms, faster than 80.16% of JavaScript online submissions for Roman to Integer.
// Memory Usage: 47.5 MB, less than 18.15% of JavaScript online submissions for Roman to Integer.