class Solution {
public:
int reverse(int x)
{
#if 0 //可以用这部分简洁的、
int ans = 0, lo = INT_MIN / 10, hi = INT_MAX / 10;
while (x) {
if (ans < lo || ans > hi)
return 0;
int r = x % 10;
ans = ans * 10;
if (r < 0 && ans < INT_MIN - r || r > 0 && ans > INT_MAX - r)
return 0;
ans += r;
x /= 10;
}
return ans;
#endif
int Symbol = 1;
if (x < 0)
{
Symbol *= -1;
}
long long res = x;
res = abs(res);
queue<int> q1;
while (res)
{
int a = res % 10;
if (a != 0)
{
res /= 10;
q1.push(a);
}
else
{
if (res >= 10)
{
q1.push(a);
}
res /= 10;
}
}
int _size = q1.size();
long long mares_inderes = 1;
for (int i = 1; i < _size; i++)
{
mares_inderes *= 10;
}
long long sum = 0;
while (!q1.empty())
{
long long a = q1.front();
q1.pop();
sum += a*mares_inderes;
mares_inderes /= 10;
}
sum *= Symbol;
if (Symbol == 1)
{
if (sum > INT_MAX)
return 0;
}
else if (Symbol == -1)
{
if (sum < INT_MIN)
return 0;
}
return (int)sum;
}
};
void main()
{
Solution s1;
int a = INT_MIN;
std::cout << "input:" << a << std::endl;
std::cout << s1.reverse(a) << std::endl;
system("pause");
}
LeetCode Reverse Integer C++
最新推荐文章于 2019-05-13 18:48:42 发布