Skip to content

Commit ae38b95

Browse files
committed
Update Java: 7. Reverse Integer
1 parent 191c61c commit ae38b95

File tree

1 file changed

+10
-16
lines changed

1 file changed

+10
-16
lines changed

java/7-Reverse-Integer.java

Lines changed: 10 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,19 @@
11
class Solution {
2-
32
public int reverse(int x) {
4-
int min = Integer.MIN_VALUE;
5-
int max = Integer.MAX_VALUE;
3+
boolean isNegative = x < 0;
64

7-
int res = 0;
8-
while (x != 0) {
9-
int digit = x % 10;
10-
x = x / 10;
5+
x = Math.abs(x);
116

12-
if (
13-
(res > max / 10) || (res == max / 10 && digit >= max % 10)
14-
) return 0;
7+
int num = 0;
158

16-
if (
17-
(res < min / 10) || (res == min / 10 && digit <= min % 10)
18-
) return 0;
9+
while(x > 0) {
10+
if (Integer.MAX_VALUE/10 < num)
11+
return 0;
1912

20-
res = (res * 10) + digit;
13+
num = 10*num + x%10;
14+
x /= 10;
2115
}
2216

23-
return res;
17+
return isNegative? -num : num;
2418
}
25-
}
19+
}

0 commit comments

Comments
 (0)