-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseInteger.java
More file actions
46 lines (34 loc) · 957 Bytes
/
Copy pathReverseInteger.java
File metadata and controls
46 lines (34 loc) · 957 Bytes
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
public class ReverseInteger {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(reverse(1534236469));
System.out.println(reverse(-123));
}
public static int reverse(int x) {
String str = x + "";
StringBuilder input = new StringBuilder();
// if it was negative, mark it and remove the negative sign
char[] strArr = str.toCharArray();
boolean neg = false;
if (strArr[0] == '-') {
str = str.substring(1, strArr.length);
neg = true;
}
// append a string into StringBuilder input
input.append(str);
// reverse StringBuilder input
input.reverse();
// put the negative back into reversed String if necessary
if (neg) {
str = "-" + input.toString();
} else {
str = input.toString();
}
Integer num = 0;
try {
num = Integer.valueOf(str);
} catch (Exception e) {
}
return num;
}
}