Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123 Output: 321
Example 2:
Input: -123 Output: -321
Example 3:
Input: 120 Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
注意:输入进去的时候符合int的范围,反转后就可能超了,事实证明有这样的测试数据。
我的ac code
class Solution {
public int reverse(int x) {
boolean flag=false;
if(x<0) {
flag=true;
x=-x;
}
String str=""+x;
while(str.charAt(str.length()-1)=='0'&&str.length()!=1) {
str=str.substring(0, str.length()-1);
}
System.out.println(str);
String re="";
for(int i=str.length()-1;i>=0;i--) {
re=re+str.charAt(i);
}
int num=0;
try {
num=Integer.parseInt(re);
}catch (Exception e) {
return 0;
}
if(flag) {
return -num;
}
return num;
}
}