题目描述:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
题目分析:
首先这个题目是将一个整数给逆转然后输出,保持符号不变.
大体的思路就是不断地模10,然后加到结果上面.结果再乘10.
几个注意的点:
1.取模之前需要取绝对值
2.越界情况:
(1) 原数不越界,取了绝对值越界.
(2) 原数不越界,逆转了之后越界.
对于上述两种情况我们直接输出0就可以了.
代码:
#include<cmath>
class Solution {
public:
int reverse(int x) {
int flag;
if(x>0){
flag=1;
}
else if(x<0){
flag=-1;
}
else{
return 0;
}
if(x==-2147483648)
return 0;
int a=abs(x);
long long res=0;
while(a!=0){
res+=a%10;
res*=10;
a/=10;
}
res/=10;
//cout<<res<<endl;
if(res>=2147483648)
return 0;
return (int)res*flag;
}
};