File tree Expand file tree Collapse file tree
solution/src/main/java/com/inuker/solution
test/src/main/java/com/inuker/test Expand file tree Collapse file tree Original file line number Diff line number Diff line change 66
77public 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 ;
Original file line number Diff line number Diff 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}
You can’t perform that action at this time.
0 commit comments