-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathreverseInteger.java
More file actions
55 lines (55 loc) · 1.7 KB
/
reverseInteger.java
File metadata and controls
55 lines (55 loc) · 1.7 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import java.util.*;
public class reverseInteger {
/* Given a 32-bit signed integer, reverse digits of an integer.
Example:
Input: -120
Output: -21
* */
public static void main(String[] args){
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.MIN_VALUE);
System.out.println(reverse(-1000));
System.out.println(reverseI(-1010));
}
/* Approach 1:
We can build up the reverse integer one digit at a time.
While doing so, we can check beforehand whether or not appending another digit would cause overflow.
* */
public static int reverseI(int x){
int res = 0;
while(x != 0){
int tail = x % 10;
if(res > Integer.MAX_VALUE/10 || (res == Integer.MAX_VALUE/10 && tail > 7)){
return 0;
}
if(res < Integer.MIN_VALUE/10 || (res == Integer.MIN_VALUE/10 && tail < -8)){
return 0;
}
/* 不能在这一步时直接跟 MIN/MAX比较,因为已经over flow了
* */
res = res * 10 + tail;
x /= 10;
}
return res;
}
/* 作弊解法:catch exception
* */
public static int reverse(int x){
int res = 0;
String orn = String.valueOf(x);
boolean isnegative = (orn.charAt(0) == '-' ? true : false);
if(isnegative){
orn = orn.substring(1);
}
String rev = new StringBuilder(orn).reverse().toString();
if(isnegative){
rev ="-"+rev;
}
try{
res = Integer.parseInt(rev);
}catch(NumberFormatException e){
res = 0;
}
return res;
}
}