-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseInteger7.java
More file actions
38 lines (35 loc) · 1.04 KB
/
ReverseInteger7.java
File metadata and controls
38 lines (35 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package easy;
public class ReverseInteger7 {
public int reverse(int x) {
if (x == 0) {
return 0;
}
int tag;
if (x < 0) {
tag = -1;
} else {
tag = 1;
}
long tmp = Math.abs((long)x);
StringBuilder sb = new StringBuilder(String.valueOf(tmp));
String result = sb.reverse().toString();
while(result.charAt(0) == '0') {
result = result.substring(1, result.length());
}
if (tag == 1) {
if (Long.parseLong(result) > (long) Integer.MAX_VALUE) {
return 0;
}
}
if (tag == -1) {
if (Long.parseLong(result) > (long) Integer.MAX_VALUE + 1) {
return 0;
}
}
return Integer.parseInt(result) * tag;
}
public static void main(String[] args) {
System.out.println(Integer.parseInt("1534236469"));
System.out.println(Integer.parseInt(new StringBuilder("1534236469").reverse().toString()));
}
}