-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path13.js
More file actions
43 lines (37 loc) · 673 Bytes
/
13.js
File metadata and controls
43 lines (37 loc) · 673 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
35
36
37
38
39
40
41
42
43
// 13_Roman to Integer
const romanToInt = function (s) {
const compare = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000,
};
const specialCompare = {
IV:4,
IX:9,
XL:40,
XC:90,
CD:400,
CM:900,
}
let romanNum = s;
let sArr = s.split("");
let sum = 0;
// check special circumstance
Object.keys(specialCompare).forEach(key=>{
if (romanNum.includes(key)) {
sum += specialCompare[key];
sArr.splice(s.indexOf(key), 2);
s = sArr.join("");
}
})
for (romanNum of sArr) {
sum += compare[romanNum];
}
console.log(sum);
return sum;
};
romanToInt("MCMXCIV"); // 1994