-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathproblem_216.js
More file actions
42 lines (40 loc) Β· 792 Bytes
/
problem_216.js
File metadata and controls
42 lines (40 loc) Β· 792 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
/**
* Converts roman numerals to decimal
* @param {string} numeral
* @return {number}
*/
function formatRomanNumerals(numeral) {
let res = 0;
const romanMap = {
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
};
for (let i = 0; i < numeral.length; i++) {
if (i === numeral.length) {
res += romanMap[numeral[i]];
break;
}
const combine = numeral[i] + numeral[i + 1];
if (romanMap[combine]) {
res += romanMap[combine];
i++;
continue;
}
res += romanMap[numeral[i]];
}
return res;
}
console.log(formatRomanNumerals('XIV')); // 14
console.log(formatRomanNumerals('IV')); // 4
console.log(formatRomanNumerals('XL')); // 40