Description
Reverse digits of an integer.
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
Example
Example1: x = 123, return 321
Example2: x = -123, return -321
Discussion
这道题为整数的逆序问题,注意溢出的处理就可以了。
算法的时间复杂度为O(1)。
C++ Code
class Solution {
public:
int reverse(int x) {
long long answer = 0;
const int maxInt = 0x7fffffff;
const int minInt = 0x80000000;
while(x != 0)
{
int num = x % 10;
answer = answer * 10 + num;
if(answer > maxInt || answer < minInt)
{
return 0;
}
x = x / 10;
}
return answer;
}
};