-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroman-to-integer_0526.html
75 lines (66 loc) · 1.5 KB
/
roman-to-integer_0526.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>roman-to-integer</title>
</head>
<body></body>
<script>
/**
* @param {string} s
* @return {number}
*/
var romanToInt = function (s) {
let obj = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000,
IV: 4,
IX: 9,
XL: 40,
XC: 90,
CD: 400,
CM: 900,
};
let count = 0;
const arr = s.split("");
for (let i = 0; i < arr.length; i++) {
let type = arr[i];
let nextType = arr[i + 1];
const addBySpecialType = () => {
count += obj[type + nextType];
i++;
};
const addAsNormal = () => {
count += obj[type];
};
if (type == "I") {
nextType == "V" || nextType == "X"
? addBySpecialType()
: addAsNormal();
continue;
}
if (type == "X") {
nextType == "L" || nextType == "C"
? addBySpecialType()
: addAsNormal();
continue;
}
if (type == "C") {
nextType == "D" || nextType == "M"
? addBySpecialType()
: addAsNormal();
continue;
}
addAsNormal();
}
return count;
};
</script>
</html>