-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathS0007.java
More file actions
42 lines (38 loc) · 937 Bytes
/
Copy pathS0007.java
File metadata and controls
42 lines (38 loc) · 937 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
/**
* 给定一个32位有符号整数,将其逆序输出。
* 假设处理环境仅能存储32位有符号整数,当逆序后的整数溢出时返回0。
*/
package leetcode.string.basic.easy;
public class S0007 {
public int reverse(int x) {
if(x == 0){
return x;
}
String s = x + "";
if(s.charAt(s.length()-1) == '0'){
s = s.substring(0, s.length()-1);
}
String symbol = "";
if(x<0){
symbol = "-";
s = s.substring(1,s.length());
}else{
symbol = "+";
}
String s2 = "";
for (int i = s.length()-1; i >=0; i--) {
s2 = s2 + s.charAt(i);
}
long result = Long.parseLong(symbol + s2);
if(result > Integer.MAX_VALUE || result<Integer.MIN_VALUE){
return 0;
}
return (int)result;
}
public static void main(String[] args) {
S0007 sol = new S0007();
int x = -123;
int result = sol.reverse(x);
System.out.println(result);
}
}