【代码】整数反转

前言

LeetCode答案,语言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
class Solution {
public int reverse(int x) {

String str = Integer.toString(x);
char[] result = new char[str.length()];

if ((str.charAt(0)+"").equals("-")) {
result[0] = "-".charAt(0);
int index = 1;
for (int i = str.length()-1; i > 0; i--) {
result[index] = str.charAt(i);
index++;
}
} else {
int index = 0;
for (int i = str.length()-1; i >= 0; i--) {
result[index] = str.charAt(i);
index++;
}
}

String res = new String(result);
int r = 0;

try {
r = Integer.parseInt(res);
} catch (Exception e) {
return 0;
}

return r;

}
}

完成