File tree Expand file tree Collapse file tree 2 files changed +30
-1
lines changed
main/java/com/fishercoder/solutions
test/java/com/fishercoder Expand file tree Collapse file tree 2 files changed +30
-1
lines changed Original file line number Diff line number Diff line change @@ -31,11 +31,30 @@ public int reverse(int x) {
31
31
while (x != 0 ) {
32
32
result = result * 10 + x % 10 ;
33
33
x /= 10 ;
34
+ System .out .println ("result = " + result );
34
35
if (result > Integer .MAX_VALUE || result < Integer .MIN_VALUE ) {
36
+ System .out .println ("break out.." );
35
37
return 0 ;
36
38
}
37
39
}
38
40
return (int ) result ;
39
41
}
40
42
}
43
+
44
+ public static class Solution2 {
45
+ /**credit: https://leetcode.com/problems/reverse-integer/discuss/4060/My-accepted-15-lines-of-code-for-Java*/
46
+ public int reverse (int x ) {
47
+ int result = 0 ;
48
+ while (x != 0 ) {
49
+ int lastDigit = x % 10 ;
50
+ int newResult = result * 10 + lastDigit ;
51
+ if (result != (newResult - lastDigit ) / 10 ) {
52
+ return 0 ;
53
+ }
54
+ x /= 10 ;
55
+ result = newResult ;
56
+ }
57
+ return result ;
58
+ }
59
+ }
41
60
}
Original file line number Diff line number Diff line change 8
8
9
9
public class _7Test {
10
10
private static _7 .Solution1 solution1 ;
11
+ private static _7 .Solution2 solution2 ;
11
12
12
13
@ BeforeClass
13
14
public static void setup () {
14
15
solution1 = new _7 .Solution1 ();
16
+ solution2 = new _7 .Solution2 ();
15
17
}
16
18
17
19
@ Test
18
20
public void test1 () {
19
- // its reversed number is greater than Integer.MAX_VALUE, thus return 0
21
+ /** its reversed number is greater than Integer.MAX_VALUE, thus return 0*/
20
22
assertEquals (0 , solution1 .reverse (1534236469 ));
23
+ System .out .println (Integer .MAX_VALUE );
24
+ System .out .println (1534236469 );
25
+ System .out .println (Integer .MAX_VALUE - 1534236469 );
26
+ }
27
+
28
+ @ Test
29
+ public void test2 () {
30
+ assertEquals (0 , solution2 .reverse (1534236469 ));
21
31
}
22
32
23
33
}
You can’t perform that action at this time.
0 commit comments