Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
难度:简单
该题和190有点接近,但是此处需要注意的是数字翻转后,导致的结果大于int类型所能容纳的范围,所以需要catch一下异常
代码:
public class Solution {
public int reverse(int n) {
String str;
StringBuffer re=new StringBuffer();
if(n>0){
str=String.valueOf(n);
char[] ch=str.toCharArray();
int result;
for(int i=ch.length-1;i>=0;i--){
System.out.println(i);
re.append(ch[i]);
}
try{
result=Integer.parseInt(re.toString());
}catch(Exception e){
result=0;
}
return result;
}else if(n<0){
str=String.valueOf(-n);
char[] ch=str.toCharArray();
int result;
for(int i=ch.length-1;i>=0;i--){
re.append(ch[i]);
}
try{
result=Integer.parseInt(re.toString());
}catch(Exception e){
result=0;
}
return -result;
}else
return 0;
}
}