Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
思路:题目本身简单的不能再简单了,但是其中有一个边界问题,也是这个题目存在的道理,就是当输出的整数没有越界,而转置之后的整数可能会越界。比如 1534236469本身并没有越界,而转置之后就9646324351就越界了。代码如下(已通过leetcode)
public class Solution {
public int reverse(int x) throws NumberFormatException {
String s=""+x;
String res="";
int ans;
//System.out.println(s);
if(x>=0) {
for(int i=s.length()-1;i>=0;i--) {
res+=s.charAt(i);
}
}
else {
res=res+s.charAt(0);
for(int i=s.length()-1;i>0;i--) {
res+=s.charAt(i);
}
}
try{
//System.out.println(res);
ans=Integer.parseInt(res);
return ans;
} catch (NumberFormatException e) {
return 0;
}
}
}