一、介绍
1.题目描述
题目链接:https://leetcode-cn.com/problems/reverse-integer/
Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
给你一个 32 位的有符号整数 x ,返回将 x 中的数字部分反转后的结果。
如果反转后整数超过 32 位的有符号整数的范围 [−231, 231 − 1] ,就返回 0。
假设环境不允许存储 64 位整数(有符号或无符号)。
注意事项:
- 注意边界条件
- 不允许存储64位整数
2.测试样例
123
-123
120
0
二、题解🟡
(1)
在不考虑边界的情况下,以-123为例,核心过程就是:
1、先将最终结果rev置0。
2、x % 10 = 余数
3、x /= 10
4、rev = rev * 10 + yu
5、当x不为0时循环 234 步骤
轮数 | 1 | 2 | 3 | 4 |
x | -123 | -123 / 10 = -12 | -1 | 0 |
yu(余数) | -123 % 10 = -3 | -12 % 10 = -2 | -1 | 0 |
rev(答案) | 0 | 0 * 10 + (-3)=-3 | -32 | -321 |
(2)
1、题目对数字大小有要求,因此要考虑边界情况。原数字和反转后的数字范围[, - 1],其中 = -2147483648 = INT_MIN, - 1 = 2147483647 = INT_MAX。
2、原数字必定满足条件。最终结果为最后一步的 rev * 10 + yu,也要满足
对于右半边,可以转化为
3、分类讨论,
⑤同理可以推导出负数的边界条件,加入到我们的代码中
class Solution {
public:
int reverse(int x) {
if(x==0) return 0;
int rev=0,yu;
while(x!=0){
yu=x%10;
x/=10;
// 边界判断
if(INT_MIN/10>rev||rev>INT_MAX/10) return 0;
rev=rev*10+yu;
}
return rev;
}
};