1.题目
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
示例 1:
输入: 123
输出: 321
示例 2:
输入: -123
输出: -321
示例 3:
输入: 120
输出: 21
注意:
假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-integer
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2.我的题解
2.1 long long 防止越界
注意越界!
class Solution {
public:
int reverse(int x) {
long long res=0;
int sign=x>0?1:-1;
long long xx=sign*(long)x;
while(xx){
res = res * 10 + xx % 10;
xx/=10;
}
res*=sign;
if(res>INT_MAX || res<INT_MIN)return 0;
return res;
}
};
3.别人的题解
3.1 提前判断越界
- 负数模正数还是负数,符号仅取决于前面的数。
class Solution {
public:
int reverse(int x) {
int res=0;
while(x){
int temp=x%10;
if(res>INT_MAX/10 || res<INT_MIN/10)return 0;
res = res*10+temp;
x/=10;
}
return res;
}
};
4.总结与反思
(1)溢出判断;
来源:CSDN
作者:永封
链接:https://blog.csdn.net/weixin_43951240/article/details/104303101