7. Reverse Integer
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Solution:
class Solution {
public:
int reverse(int x) {
int tmp=0, neg=0;
long long ans=0;
if(x==0) return 0;
else if(x<0){
neg=1;
x*=-1;
}
while(x){
tmp=x%10;
ans*=10;
ans+=tmp;
x/=10;
}
if(neg) ans*=-1;
return (ans<INT_MIN || ans>INT_MAX) ? 0 : ans;
}
};
注意的地方:
1、中间加法过程可能溢出。
2、结果溢出时要返回0。
3、注意输入的整数中间有的0情况。