-
Notifications
You must be signed in to change notification settings - Fork 0
/
7.Reverse_Integer.java
59 lines (58 loc) · 1.69 KB
/
7.Reverse_Integer.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
58
59
class Solution {
public int reverse(int x) {
int val = Math.abs(x);
int rev = 0;
while (val>0) {
if (Integer.MAX_VALUE/10 < rev) {
return 0;
}
rev *= 10;
rev += val%10;
val /= 10;
}
return x<0 ? -rev : rev;
}
}
class Solution {
public int reverse(int x) {
char[] min = String.valueOf(Integer.MIN_VALUE).toCharArray();
char[] max = String.valueOf(Integer.MAX_VALUE).toCharArray();
char[] num = String.valueOf(x).toCharArray();
int n = num.length;
char[] rev = new char[n];
if (num[0] == '-') {
rev[0] = '-';
for (int i=1; i<n; i++) {
rev[n-i] = num[i];
}
if (rev.length == min.length) {
for (int i=0; i<n; i++) {
if (rev[i] > min[i]) {
return 0;
} else if (rev[i] < min[i]) {
break;
} else {
continue;
}
}
}
return Integer.valueOf(new String(rev));
} else {
for (int i=0; i<n; i++) {
rev[n-1-i] = num[i];
}
if (rev.length == max.length) {
for (int i=0; i<n; i++) {
if (rev[i] > max[i]) {
return 0;
} else if (rev[i] < max[i]) {
break;
} else {
continue;
}
}
}
return Integer.valueOf(new String(rev));
}
}
}