Reverse Integer
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
分析:
求余求商迭代到最后商为0,注意:翻转后的数可能会越界,做好处理
代码:
class Solution {
public:
int reverse(int x) {
long res=0;
int res1;
int flag=0;
int yu;
if(x<0)
{
flag=1;
x=0-x;
}
while(x)
{
yu=x%10;
x/=10;
res*=10;
res+=yu;
}
if(flag==1)
{
res=0-res;
}
res1=(int)res;
if((long)res1!=res)
res1=0;
return res1;
}
};