Reverse Integer
7. Reverse Integer
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
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1].
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
int reverse(int x) {
int i = 0;
int y = 0;
__int64_t sum = 0;
while(x != 0)
{
i++;
y = x % 10;
if(i == 1 && y == 0)
{
continue;
}
sum = sum * 10 + y;
if (sum > (pow(2, 31) - 1) || sum < (-pow(2, 31)))
{
return 0;
}
x /= 10;
}
return sum;
}
需要注意的问题就是翻转的数据有可能会超出int类型的范围,所以用了__int64_t(-2^63 ~ 2^63-1)存储翻转的数据,用以比较反转的数据是否在int类型范围内

浙公网安备 33010602011771号