-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRoman to Integer.js
98 lines (95 loc) · 2.61 KB
/
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
94
95
96
97
98
/*Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.*/
/**
* @param {string} s
* @return {number}
*/
// L 50 C 100 D 500 M 1000
// eg: 998 - DCCCCLXXXXVIII
var romanToInt = function(s) {
val = 0
s = s.split('')
var flag = false
for(i=0; i<s.length;){
switch(s[i]){
case 'M': val += 1000
i++
break
case 'D': val += 500
i++
break
case 'C':
if(s[i+1]){
if(s[i+1] != 'D' && s[i+1] != 'M'){
val += 100
i++
break
}else{
val -= 100
i++
break
}
}
else{
val += 100
i++
break
}
case 'L': val += 50
i++
break
case 'X':
if(s[i+1]){
if(s[i+1] != 'L' && s[i+1] != 'C'){
val += 10
i++
break
}else{
val -= 10
i++
break
}
}
else{
val += 10
i++
break
}
case 'V': val += 5
i++
break
case 'I':
if(s[i+1]){
if(s[i+1] != 'I'){
val -= 1
i++
break
}
else{ // s[i+1] = 'I' -> II
if(s[i+2]){ // has to be an I
if(s[i+3]){ // has to be an I
val += 3
i += 3
break
} // no s[i+3]
else{
val += 2
i += 2
break
}
}
else{
val += 2
i += 2
break
}
}
}
else{
val += 1
i++
}
}
}
return val
};