Reverse Integer
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 typedef long long lld; 2 lld mn=-((lld)1<<32-1); 3 lld mx=(lld)1<<32-1; 4 class Solution { 5 public: 6 int reverse(int x) { 7 lld ans=0; 8 int sign=0; 9 if(x<0) 10 { 11 sign=1; 12 x=-x; 13 } 14 while(x) 15 { 16 ans=ans*10+x%10; 17 x/=10; 18 } 19 if(sign) 20 ans=-ans; 21 if(ans>mx||ans<mn) 22 ans=0; 23 return (int)ans; 24 } 25 };
1、求int的最大最小值可以用位运算,用long int 保存
2、用取余法得到reverse的数,就可以不用考虑前导零,只需要考虑负数和溢出情况
3、根据负数取余仍旧是负数,-8%10=-8 ,-52%10=-2
所以也可以不考虑负数情况
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 typedef long long lld; 2 lld mn=-(lld)1<<32; 3 lld mx=(lld)1<<32-1; 4 class Solution { 5 public: 6 int reverse(int x) { 7 lld ans=0; 8 while(x) 9 { 10 ans=ans*10+x%10; 11 x/=10; 12 } 13 if(ans>mx||ans<mn) 14 ans=0; 15 return (int)ans; 16 } 17 };