
public static int reverse(int x) {
// 接受反转的值
long a =0;
int sign = 1;
// 当是一位数时,直接返回,反转的值也是一样
if(x>=-9 && x<=9 ){
return x;
}
// 当值最小时,反转后超过int的范围。直接返回0
if(x <= Integer.MIN_VALUE){
return 0;
}
// 将值转为字符串进行读取
String s = String.valueOf(x);
// 判断第一位是否是符号位
char c = s.charAt(0);
if('-' == c || '+' == c){
sign = '-' == c ? -1 : 1;
// 进行重新赋值
x = Integer.parseInt(s.substring(1,s.length()));
}
// 进行重新赋值
s =String.valueOf(x);
// 取字符串长度
int length = s.length();
// 倒序进行拼接
for (int i = length-1; i >= 0; i--) {
char c1 = s.charAt(i);
int i1 = c1 - '0';
a = a*10+i1;
// 判断是否超过Integer 的范围
if(a*sign > Integer.MAX_VALUE || a*sign < Integer.MIN_VALUE){
return 0;
}
}
return (int) a*sign;
}