/**
* 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.
*/
#include <iostream>
using namespace std;
class Solution{
public:
int reverse(int x){
const int max = 0x7fffffff; //max number
const int min = 0x80000000; //min number
long long sum = 0;
while(x != 0)
{
int temp=x%10;
sum = sum*10+temp;
if(sum>max||sum<min) //溢出操作
{
//sum=sum>0?max:min;
//return sum;
return 0;
}
x = x/10;
}
return sum;
}
};
int main()
{
Solution s;
cout << s.reverse(123) << endl;
cout << s.reverse(-123) << endl;
cout << s.reverse(10100) << endl;
cout << s.reverse(1000000003) << endl; //反转之后溢出最大值
//const int maxn = 0x7fffffff;
//cout << "最大值:"<<maxn << endl;
return 0;
}
leetcode Reverse Integer
最新推荐文章于 2018-08-12 17:49:21 发布