- Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
注意:这里的注意需要仔细看,确保你的环境能存储int的32位,确保你的函数返回0当int越界的时候。所以当输入大于10位的int,你得小心判断,可能int就存放不了。
解法一:我用到了字符串转置求逆序,但是最后字符串变int时:如果给的数字大于Integer.MAX_VALUE,或者小于Integer.MIN_VALUE时,会导致转换失败,且比较难解决。我想过转化为bigInt,但是不能转化回来。
//这里有个坑,因为int是32位,范围是-2,147,483,648~2,147,483,647,所以如果解决办法是字符串电话,在大于10位时会报错,无法转换。
public static int reverse(int x) {
String str = String.valueOf(x);
String str1 = new StringBuilder(str).reverse().toString();
String res;
if (str1.contains("-")){
str1 = str1.replace("-","");
res = "-";
}else {
res = "";
}
Boolean flag = false;
for (char c: str1.toCharArray()){
if (Integer.parseInt(String.valueOf(c))>=0){
flag=true;
if (flag){
res+=c;
}
}
}
return Integer.parseInt(res);
}
解法二:利用取余的方式对结果进行倒序,且每次循环对结果进行判断,如果大于Integer.MAX_VALUE,或者小于Integer.MIN_VALUE时返回0;
//用整除解决 -2,147,483,648~2,147,483,647
public static int reverse1(int x) {
int res = 0;
while (x!=0){
int pop = x%10;
x = x/10;
if (res>Integer.MAX_VALUE/10 || (res== Integer.MAX_VALUE/10 && pop >7)) return 0 ;//判断2147483647
if (res<Integer.MIN_VALUE/10 || (res==Integer.MIN_VALUE/10 && pop<-8)) return 0;//判断-2147483648
res = res*10 +pop;
}
return res;
}