问题链接
问题描述
反转一个整数
例一: x = 123, 返回 321
例二: x = -123, 返回 -321
解决方法
public class Solution {
public int reverse(int x) {
int absNumber = Math.abs(x);
if(absNumber > 0 && absNumber < 10){
return x;
}
String numberString = Integer.toString(absNumber);
if(numberString.indexOf("-") == 0){
numberString = numberString.substring(1);
}
String reverseNumberString = "";
int lastPosition = numberString.length()-1;
for(int i = lastPosition;i>=0;i--){
String a = String.valueOf(numberString.charAt(i));
if(!(a.equals("0") && reverseNumberString.equals(""))){
reverseNumberString += a;
}
}
try{
int reverseNumber = Integer.parseInt(reverseNumberString);
if(x<0){
return -reverseNumber;
}
return reverseNumber;
}catch(NumberFormatException e){
return 0;
}
}
}