Skip to content

Commit 8adbb73

Browse files
committed
Fixed duplicate.
1 parent e1fe9ad commit 8adbb73

File tree

1 file changed

+16
-27
lines changed

1 file changed

+16
-27
lines changed

src/main/java/s0013_roman_to_integer/Solution.java

Lines changed: 16 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -8,43 +8,19 @@ public int romanToInt(String s) {
88
y = s.charAt(i);
99
switch (y) {
1010
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');
2012
break;
2113
case 'V':
2214
x += 5;
2315
break;
2416
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');
3418
break;
3519
case 'L':
3620
x += 50;
3721
break;
3822
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');
4824
break;
4925
case 'D':
5026
x += 500;
@@ -58,4 +34,17 @@ public int romanToInt(String s) {
5834
}
5935
return x;
6036
}
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+
}
6150
}

0 commit comments

Comments
 (0)