Skip to content

Commit 677392a

Browse files
committed
fd
1 parent 45b83f8 commit 677392a

File tree

2 files changed

+13
-14
lines changed

2 files changed

+13
-14
lines changed

solution/src/main/java/com/inuker/solution/ReverseInteger.java

Lines changed: 0 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -6,20 +6,6 @@
66

77
public class ReverseInteger {
88

9-
// 耗时43ms
10-
public int reverse(int x) {
11-
long y = x;
12-
int sign = y > 0 ? 1 : -1;
13-
y = y > 0 ? y : -y;
14-
String s = String.valueOf(y);
15-
s = new StringBuilder(s).reverse().toString();
16-
y = Long.valueOf(s) * sign;
17-
if (y > Integer.MAX_VALUE || y < Integer.MIN_VALUE) {
18-
return 0;
19-
}
20-
return (int) y;
21-
}
22-
239
// 耗时40ms
2410
public int reverse2(int x) {
2511
long y = x, r = 0;

test/src/main/java/com/inuker/test/main.java

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,4 +35,17 @@ public static void main(String[] args) {
3535
System.out.print(n + " ");
3636
}
3737
}
38+
39+
public int reverse(int x) {
40+
int sign = x > 0 ? 1 : -1;
41+
long y = Math.abs(x), z = 0;
42+
for ( ; y > 0; y /= 10) {
43+
z = z * 10 + y % 10;
44+
}
45+
z *= sign;
46+
if (z > Integer.MAX_VALUE || z < Integer.MIN_VALUE) {
47+
throw new IllegalStateException();
48+
}
49+
return (int) z;
50+
}
3851
}

0 commit comments

Comments
 (0)