if(x>=0&& x<=2147483647){//省略的代码//将String类型转化为long类型//用long类型作为过渡(接收结果)
result =Long.parseLong(str);if( result >2147483647){//如果结果已经大于int类型范围就直接返回0return0;}else{//如果结果没有超出int类型范围最后转化为int类型return(int)result;}
整体代码如下
importjava.util.Arrays;publicclassReserveInteger{publicstaticintreserve(int x){long result =0;if(x>=0&& x<=2147483647){if(x >0){char[] chars =String.valueOf(x).toCharArray();char[] chars1 =newchar[chars.length];for(int i =0; i <= chars.length -1; i++){
chars1[i]= chars[chars.length -1- i];}String str =newString(chars1);
result =Long.parseLong(str);if( result >2147483647){return0;}else{return(int)result;}}elseif(x < 0 && x >=-2147483648){char[] chars =String.valueOf(x).toCharArray();char[] chars1 =newchar[chars.length];for(int i =0; i <= chars.length -1; i++){
chars1[i]= chars[chars.length -1- i];}char[] chars2 =Arrays.copyOfRange(chars1,0, chars1.length -1);String str =newString(chars2);
result =Long.parseLong(str);if( result <-2147483648){return0;}else{return(int)result;}}else{return0;}}else{return0;}}publicstaticvoid main (String[]args){int a =-2147483412;System.out.println(reserve(a));}}