forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0013-roman-to-integer.js
93 lines (85 loc) · 2.15 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/**
* @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.
function romanToInt(s) {
let sum = 0
let next = null
const romanArr = {
"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000
}
for (let i = 0; i < s.length; i++ ) {
next = s[i + 1] || null
const curr = s[i]
if (romanArr[next] > romanArr[curr]) {
sum -= romanArr[curr]
continue
}
sum += romanArr[curr]
}
return sum
};
// Runtime 97 ms
// Memory usage: 47.8 MB
// https://leetcode.com/problems/roman-to-integer/submissions/1020204566/