給定一個範圍爲 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);
}
複製代碼