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) {
int tmp=0;
int flag=1;
if(x<0)
{
flag=-1;
x=0-x;
}
for(;x>0;)
{
int t=tmp;
tmp=tmp*10+x%10;
//判断是否溢出
if((tmp-x%10)/10 != t)
{
return 0;
}
x/=10;
}
return tmp*flag;
}
};