一、题目描述:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
二、解题:
class Solution
{
public:
int reverse(int x)
{
long res=0; //不能定义int 因为最大值int_max=2147483647,不能保证所有32位int都能反转,因为有可能越界。
while (x)
{
res = res*10 + x % 10;
x = x / 10;
}
return (res<INT_MIN || res>INT_MAX) ? 0 : res; //判断越界
}
};