题解 | #反转数字#
反转数字
http://www.nowcoder.com/practice/1a3de8b83d12437aa05694b90e02f47a
import java.util.*;
public class Solution {
/**
*
* @param x int整型
* @return int整型
*/
public int reverse (int x) {
// write code here
boolean flag = true;//true表示为正数,false为负数
if(x<0){//将负数转换为正数
flag = false;
x = -1*x;
}
String str = Integer.toUnsignedString(x);//将整形数转换为字符串
StringBuffer stringBuffer = new StringBuffer(str);
String str1 = stringBuffer.reverse().toString();//将字符串翻转
long y = Long.parseLong(str1);//将为字符串转换长整形数
int max = (int)Math.pow(2,32)-1;//整形数的最大值
int min = (int)Math.pow(2,32)*(-1);//整形数的最小值
if(flag){//正数处理
if(y>max){//溢出处理
return 0;
}else{
return (int)y;
}
}else{//负数处理
y = -1*y;
if(y<min){//溢出处理
return 0;
}else{
return (int)y;
}
}
}
}