题目
整数翻转(溢出问题&取余取模)
https://leetcode-cn.com/problems/reverse-integer/
题解
基础知识点:
- 除法取余 & 取模
- 考虑整数溢出的情况
- 边除边乘。最开始我的想法是把数字按位数拆开,然后按照幂次规律乘,但是这个麻烦的地方在于并不知道有几位数,所以题解中采用了每次*10,不断嵌套
优秀讲解:
作者:guanpengchn
链接:https://leetcode-cn.com/problems/reverse-integer/solution/hua-jie-suan-fa-7-zheng-shu-fan-zhuan-by-guanpengc/
来源:力扣(LeetCode)
标签:数学
本题如果不考虑溢出问题,是非常简单的。解决溢出问题有两个思路,第一个思路是通过字符串转换加try catch的方式来解决,第二个思路就是通过数学计算来解决。
由于字符串转换的效率较低且使用较多库函数,所以解题方案不考虑该方法,而是通过数学计算来解决。
通过循环将数字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 result = 0;
int rem = 0;
while (x != 0) {
rem = x % 10;
// 在32位操作系统下int类型取值范围如下: 1、Int32 //等于int, 占4个字节(-2147483648~2147483647)
if ((result < 214748364 && result > -214748364) ||
(result == 214748364 && rem <=7) ||
(result == -214748364 && rem <=8)) {
// result = result * 10 + x % 10; // 本质用这个公式就可以
result = result * 10 + rem;
} else {
return 0;
}
x = x / 10;
}
return result;
}
};
优秀题解:
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;
}
}
优化代码:
提供一种判断溢出的思路
有两点:
- while里使用了除法,较慢
- if 语句有四种可能性,判断pop变量较多余
最大的值与最小的值为:[−2^31, 2^31 − 1], 即:[-2147483648, 2147483647]
如果y = y * 10 + x % 10溢出,则 y>=214748364 ,
当y=214748364时,输入的值只能为:1463847412,此时不溢出
即:y > 214748364 || y < -214748364 必定溢出
class Solution {
public int reverse(int x) {
int y = 0;
while (x != 0) {
if (y > 214748364 || y < -214748364) {
return 0;
}
y = y * 10 + x % 10;
x = x / 10;
}
return y;
}
}