题目:
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123 Output: 321
Example 2:
Input: -123 Output: -321
Example 3:
Input: 120 Output: 21
题目解析:这道题目比较简单,比较难处理的是溢出处理,若溢出返回0
越界处理有两种方法:方法一 每次判断res若经过下一次计算,是否会溢出,保证res不会溢出
class Solution {
public:
int reverse(int x) {
int res = 0;
while(x)
{
int tmp = x%10;
x /= 10;
if(res > INT_MAX/10 || (res == INT_MAX / 10 && tmp > 7))
return 0;
if(res < INT_MIN/10 || (res == INT_MIN / 10 && tmp < -8))
return 0;
res = res*10 + tmp;
}
return res;
}
};
方法二:使用long保存可能溢出的数,待循环结束,判读是否溢出,若溢出返回0
class Solution {
public:
int reverse(int x) {
long res = 0;
while(x)
{
int tmp = x%10;
x /= 10;
res = res*10 + tmp;
}
if(res > INT_MAX || res < INT_MIN)
return 0;
return res;
}
};