@@ -8,43 +8,19 @@ public int romanToInt(String s) {
8
8
y = s .charAt (i );
9
9
switch (y ) {
10
10
case 'I' :
11
- if (i + 1 == s .length ()) {
12
- x += 1 ;
13
- } else if (s .charAt (i + 1 ) == 'V' ) {
14
- x -= 1 ;
15
- } else if (s .charAt (i + 1 ) == 'X' ) {
16
- x -= 1 ;
17
- } else {
18
- x += 1 ;
19
- }
11
+ x = getX (s , x , i , 1 , 'V' , 'X' );
20
12
break ;
21
13
case 'V' :
22
14
x += 5 ;
23
15
break ;
24
16
case 'X' :
25
- if (i + 1 == s .length ()) {
26
- x += 10 ;
27
- } else if (s .charAt (i + 1 ) == 'L' ) {
28
- x -= 10 ;
29
- } else if (s .charAt (i + 1 ) == 'C' ) {
30
- x -= 10 ;
31
- } else {
32
- x += 10 ;
33
- }
17
+ x = getX (s , x , i , 10 , 'L' , 'C' );
34
18
break ;
35
19
case 'L' :
36
20
x += 50 ;
37
21
break ;
38
22
case 'C' :
39
- if (i + 1 == s .length ()) {
40
- x += 100 ;
41
- } else if (s .charAt (i + 1 ) == 'D' ) {
42
- x -= 100 ;
43
- } else if (s .charAt (i + 1 ) == 'M' ) {
44
- x -= 100 ;
45
- } else {
46
- x += 100 ;
47
- }
23
+ x = getX (s , x , i , 100 , 'D' , 'M' );
48
24
break ;
49
25
case 'D' :
50
26
x += 500 ;
@@ -58,4 +34,17 @@ public int romanToInt(String s) {
58
34
}
59
35
return x ;
60
36
}
37
+
38
+ private int getX (String s , int x , int i , int i2 , char v , char x2 ) {
39
+ if (i + 1 == s .length ()) {
40
+ x += i2 ;
41
+ } else if (s .charAt (i + 1 ) == v ) {
42
+ x -= i2 ;
43
+ } else if (s .charAt (i + 1 ) == x2 ) {
44
+ x -= i2 ;
45
+ } else {
46
+ x += i2 ;
47
+ }
48
+ return x ;
49
+ }
61
50
}
0 commit comments