您的位置:首页 > 其它

leetcode 7 Reverse Integer

2015-10-30 17:14 573 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: