File tree Expand file tree Collapse file tree 2 files changed +13
-14
lines changed
solution/src/main/java/com/inuker/solution
test/src/main/java/com/inuker/test Expand file tree Collapse file tree 2 files changed +13
-14
lines changed Original file line number Diff line number Diff line change 6
6
7
7
public class ReverseInteger {
8
8
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
-
23
9
// 耗时40ms
24
10
public int reverse2 (int x ) {
25
11
long y = x , r = 0 ;
Original file line number Diff line number Diff line change @@ -35,4 +35,17 @@ public static void main(String[] args) {
35
35
System .out .print (n + " " );
36
36
}
37
37
}
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
+ }
38
51
}
You can’t perform that action at this time.
0 commit comments