给定一个范围为 32 位 int 的整数,将其颠倒。java
例 1:bash
输入: 123
输出: 321
复制代码
例 2:spa
输入: -123
输出: -321
复制代码
例 3:code
输入: 120
输出: 21
复制代码
注意: 假设咱们的环境只能处理 32 位 int范围内的整数。根据这个假设, 若是颠倒后的结果超过这个范围,则返回 0。orm
这个题目其实挺简单的;思路以下:字符串
public int reverse(int x) {
int result = 0;
if (x >Integer.MAX_VALUE){
return 0 ;
}
String s =String.valueOf(x);
int len = 0;
if (s!=null&&s.length()!=0&&s.charAt(0)=='-'){
len = 1;
}else if(s.length() == 1){
return x;
}
int lastp = s.length()-1;
boolean isStart = true;
String ints = "";
while( lastp >= len){
if (isStart && s.charAt(lastp)=='0'){
while (s.charAt(lastp)=='0'){
lastp--;
}
isStart = false;
}
if (isStart){
isStart = false;
}
ints = ints+s.charAt(lastp);
lastp--;
}
try{
result = Integer.parseInt(ints);
}catch (NumberFormatException e){
return 0;
}
return len==0?result:result*(-1);
}
复制代码