题目:
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
示例 1:
输入: 123
输出: 321
示例 2:
输入: -123
输出: -321
示例 3:
输入: 120
输出: 21
注意:
假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。
请根据这个假设,如果反转后整数溢出那么就返回 0。
解法一:
使用String的一些函数
public int reverse(int x) {
if(x == 0 || x > Integer.MAX_VALUE || x < Integer.MIN_VALUE){
return 0;
}
String str = String.valueOf(x);
String res = "";
if(str.contains("-")){
res = res + "-";
}
str = str.replaceAll("-","");
Boolean resBoolean = false;//是否往res中开始添加真实值,如果添加过则为true,如果没有则为false
for(int i = str.length() - 1; i >= 0; i--){
String chartAt = String.valueOf(str.charAt(i));
if((chartAt.trim().equals("0") && !resBoolean)){
continue;
}
res = res + chartAt;
resBoolean = true;
}
Long resInt = Long.parseLong(res);
if(resInt.longValue() > Integer.MAX_VALUE || resInt.longValue() < Integer.MIN_VALUE){
return 0;
}
return resInt.intValue();
}
解法二:
不使用String函数,直接计算
图解分析:
代码:
public int reverseTwo(int x) {
if(x == 0 || x > Integer.MAX_VALUE
|| x < Integer.MIN_VALUE){
return 0;
}
Long res = 0L;
while (x != 0){
int t = x % 10;
Long newRes = res * 10 + t;
// if((newRes - t) / 10 != res){
// return 0;
// }
if(newRes.longValue() > Integer.MAX_VALUE
|| newRes.longValue() < Integer.MIN_VALUE){
return 0;
}
res = newRes;
x = x/10;
}
if(res.longValue() > Integer.MAX_VALUE
|| res.longValue() < Integer.MIN_VALUE){
return 0;
}
return res.intValue();
}