-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
50 lines (45 loc) · 1.27 KB
/
script.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
const romanToInt = function(romanNumber) {
let romanArr = [];
for (let i = 0; i < romanNumber.length; i++) {
let romanIndex = romanNumber[i];
if (romanIndex == 'I') {
romanIndex = 1;
romanArr.push(romanIndex);
} else if (romanIndex == 'V') {
romanIndex = 5;
romanArr.push(romanIndex);
} else if (romanIndex == 'X') {
romanIndex = 10;
romanArr.push(romanIndex);
} else if (romanIndex == 'L') {
romanIndex = 50;
romanArr.push(romanIndex);
} else if (romanIndex == 'C') {
romanIndex = 100;
romanArr.push(romanIndex);
} else if (romanIndex == 'D') {
romanIndex = 500;
romanArr.push(romanIndex);
} else if (romanIndex == 'M') {
romanIndex = 1000;
romanArr.push(romanIndex);
}
}
let total = 0;
if (romanArr.length == 1) {
total = total + romanArr[0];
} else {
for (let i = 0; i < romanArr.length; i++) {
if (i == (romanArr.length - 1) ) {
total = total + romanArr[i];
} else if (romanArr[i] >= (romanArr[i + 1])) {
total = total + romanArr[i];
} else if (romanArr[i] <= (romanArr[i + 1])) {
total = total - romanArr[i];
}
}
}
return total;
}
// Test ----> Expected output = 604
console.log(romanToInt('DCIV'));