-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathN7Reverse.java
57 lines (46 loc) · 1.31 KB
/
N7Reverse.java
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/*
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
示例 1:
输入: 123
输出: 321
溢出输出 0
*/
package LeetCode;
public class N7Reverse {
private static int solution(int x){
String s = Integer.toString(x);
s = new StringBuilder(s).reverse().toString();
int result = 0;
if(x<0){
try {
result = Integer.valueOf(s.substring(0, s.length() - 1))*-1;
} catch (Exception e){
}
}else{
try {
result = Integer.valueOf(s);
} catch (Exception e){
}
}
return result;
}
public static void main(String[] args) {
int x = 120;
//first version -- too slow.
//System.out.println(solution(x));
int pop;
int ans = 0;
while(x!=0){
pop = x%10; //取末尾
if(ans>Integer.MAX_VALUE/10||(ans==Integer.MAX_VALUE/10 && pop>7))
//return 0;
System.out.println(0);
if(ans<Integer.MIN_VALUE/10 || (ans ==Integer.MIN_VALUE/10 && pop<-8))
// return 0
System.out.println(0);
ans = ans*10+pop;
x = x/10;
}
System.out.println(ans);
}
}