给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
实例:输入: -123 输出: -321
一.分析
这个题的关键是判断反转后的整数是否还在范围内,若超出范围,则称为“溢出”。
如何判断是否“溢出”呢?int32的范围为[-231,231),即[-2 147 483 648,2 147 483 648)。设当前计算结果为res,下一位为n。
1.正整数溢出条件:res10>214 748 364或者res10+n>2 147 483 647,即res>MAX_VALUE /10 或者res== MAX_VALUE / 10 且n > 7
2.负整数溢出条件:res10<-214 748 364或者res10+n<-2 147 483 648,即res<MIN_VALUE/10 或者res== MAX_VALUE / 10 且 n <-8
二.代码
package JavaArithmetic;
public class IntegerInversion {
public int IntegerInversion(int x) {
int res = 0;
while (x != 0) {
// 输出每一位的数字
int n = x % 10;
// 判断每次输出的数字会不会溢出
if (res > Integer.MAX_VALUE / 10 || (res == Integer.MAX_VALUE / 10 && n > 7))
return 0;
if (res < Integer.MIN_VALUE / 10 || (res == Integer.MIN_VALUE / 10 && n < -8))
return 0;
res = res * 10 + n;
x /= 10;
}
return res;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
IntegerInversion result = new IntegerInversion();
System.out.println(result.IntegerInversion(-1463847412));
}
}
或者我们可以把正负数和到一种情况内表示,因为有些数字我们在输入的时候已经判别为错误,超出了int范围
package JavaArithmetic;
public class IntegerInversion {
public int IntegerInversion(int x) {
int neg = x < 0 ? -1 : 1;
x *= neg;
if (x >= Integer.MAX_VALUE)
return 0;
int res = 0;
while (x > 0) {
// 输出每一位的数字
int n = x % 10;
// 判断每次输出的数字会不会溢出
if (res > Integer.MAX_VALUE / 10 || (res == Integer.MAX_VALUE / 10 && n > 7))
return 0;
res = res * 10 + n;
x /= 10;
}
return res * neg;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
IntegerInversion result = new IntegerInversion();
System.out.println(result.IntegerInversion(-1463847412));
}
}