Reverse Integer
Reverse digits of an integer
Example1 : x = 123, return 321
Example2: x = -123, return -321;
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
#include <iostream>
#include <math.h>
using namespace std;
class Solution
{
public:
int reverse(int x)
{
if (x == 0)
{
return 0;
}
int bar = 10;
int t = x;
int r;
int ret = 0;
int i = 10;
while (t != 0)<span style="white-space:pre"> </span>//将t中的数据拿出,放入ret中
{
r = t % bar;
if (x == t)
{
ret = ret + r;
}
else
{
if (ret >= 214748365 || ret <= -214748365)<span style="white-space:pre"> </span>//关于其边界问题。
{
return 0;
}
if (ret == 241748364 || ret == -241748364)<span style="white-space:pre"> </span>//关于其边界问题。
{
if (r > 8)
{
return 0;
}
}
ret = ret*i + r;
}
t = t / bar;
}
<span style="white-space:pre"> </span>return ret;
}
};
int main(int argc, char ** argv)
{
int x;
Solution so;
cin >> x;
cout << so.reverse(x);
return 0;
}