题目描述
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
示例 1:
输入: 123
输出: 321
示例 2:
输入: -123
输出: -321
示例 3:
输入: 120
输出: 21
注意:
假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−2^31, 2^31 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。
怎么判断整数溢出
思路一,通过字符串转换加try catch的方式来解决,由于字符串转换的效率较低且使用较多库函数,所以解题方案不考虑该方法。
思路二,数学计算来解决。
思路三,设置为long类型接收数字,最后判断。
方法一,数学方法
通过循环将数字x的每一位拆开,在计算新值时每一步都判断是否溢出
。
溢出条件有两个,一个是大于整数最大值MAX_VALUE,另一个是小于整数最小值MIN_VALUE,设当前计算结果为ans,下一位为pop。
从ans * 10 + pop > MAX_VALUE这个溢出条件来看
当出现 ans > MAX_VALUE / 10 且 还有pop需要添加 时,则一定溢出
当出现 ans == MAX_VALUE / 10 且 pop > 7 时,则一定溢出,7是2^31 - 1的个位数
从ans * 10 + pop < MIN_VALUE这个溢出条件来看
当出现 ans < MIN_VALUE / 10 且 还有pop需要添加 时,则一定溢出
当出现 ans == MIN_VALUE / 10 且 pop < -8 时,则一定溢出,8是-2^31的个位数
class Solution {
public int reverse(int x) {
int ans = 0;
while (x != 0) {
int pop = x % 10;
if (ans > Integer.MAX_VALUE / 10 || (ans == Integer.MAX_VALUE / 10 && pop > 7))
return 0;
if (ans < Integer.MIN_VALUE / 10 || (ans == Integer.MIN_VALUE / 10 && pop < -8))
return 0;
//反转方法。每次反转前检查溢出。
ans = ans * 10 + pop;
x /= 10;
}
return ans;
}
}
有一个技巧,将x变成正数,单独判断符号位即可,这样可以少了一个判断条件。
class Solution {
public int reverse(int x) {
int ans = 0;
int sign = 1;
//这样子要特判一些Integer.MIN_VALUE,因为x如果等于Integer.MIN_VALUE,转换为-x时,已经溢出了。
if(x == Integer.MIN_VALUE){
return 0;
}
if(x<0){
x = -x;
sign = -1;
}
while (x != 0) {
int pop = x % 10;
if (ans > Integer.MAX_VALUE / 10 || (ans == Integer.MAX_VALUE / 10 && pop > 7))
return 0;
//反转方法。每次反转前检查溢出。
ans = ans * 10 + pop;
x /= 10;
}
return ans * sign;
}
}
方法二,long类型接收
class Solution {
public int reverse(int x) {
long result = 0;
while (x != 0){
result = result * 10 + x % 10;
x = x / 10;
}
if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE){
return 0;
}
//转型。
return (int)result;
}
}