Skip to content

Commit 448e3a9

Browse files
refactor 7
1 parent e9ae98c commit 448e3a9

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

src/main/java/com/fishercoder/solutions/_7.java

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,11 +31,30 @@ public int reverse(int x) {
3131
while (x != 0) {
3232
result = result * 10 + x % 10;
3333
x /= 10;
34+
System.out.println("result = " + result);
3435
if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
36+
System.out.println("break out..");
3537
return 0;
3638
}
3739
}
3840
return (int) result;
3941
}
4042
}
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+
}
4160
}

src/test/java/com/fishercoder/_7Test.java

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,16 +8,26 @@
88

99
public class _7Test {
1010
private static _7.Solution1 solution1;
11+
private static _7.Solution2 solution2;
1112

1213
@BeforeClass
1314
public static void setup() {
1415
solution1 = new _7.Solution1();
16+
solution2 = new _7.Solution2();
1517
}
1618

1719
@Test
1820
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*/
2022
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));
2131
}
2232

2333
}

0 commit comments

Comments
 (0)