public class IntReverse {
/**
* 借助字符串反转
* @param x
* @return
*/
public int reverse(int x) {
String xStr = String.valueOf(x);
char[] chars =xStr.toCharArray();
StringBuffer tmp = new StringBuffer();
int range =0;
if(x<0) {
tmp.append("-");
range++;
}
for(int i=chars.length-1;i>=range;i--){
tmp.append(chars[i]);
}
return Integer.valueOf(tmp.toString());
}
/**
* 数学算法
* @param args
*/
public int reverse1(int x) {
int result=0;
while(x!=0){
int pop = x%10;//取最低位的值,负数取余数,余数也为负数
x = x/10;//负数取商,商也为负数
if(result>Integer.MAX_VALUE/10||(result==Integer.MAX_VALUE/10&&pop>Integer.MAX_VALUE%10)){
result=0;
break;
}
if(result<Integer.MIN_VALUE/10||(result==Integer.MIN_VALUE/10&&pop<Integer.MIN_VALUE%10)){
result=0;
break;
}
result = result*10+pop;
}
return result;
}
public static void main(String[] args){
IntReverse intReverse = new IntReverse();
int x = -1463847412;
System.out.println(intReverse.reverse1(x));
}
}
网友评论