您的位置:首页 > 理论基础 > 数据结构算法

Reverse Integer(leetcode)

2014-12-17 21:52 495 查看
题目:整数反转

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321


题目很简单,但是有些问题要注意:

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.

以下代码是自己写的通过了leetcode的测试,思路从个位数开始依次取得每个数便入队列,然后再从队列中取出合并成整数。这部分代码现在看来其实挺冗余的。队列完全不需要。其中INT_MAX,
INT_MIN是C++编译器预定义的宏量。不知道有这两个宏存在程序员就可能跟我开始一样自定义,但VS编译器,总报错。

class Solution {
public:
int reverse(int x) {
queue<int> temp;
long long ans = 0, n;

n = abs(x);
while (n % 10 || n/10) //n/10, 为了防止x为10的整数倍也能进入循环
{
temp.push(n%10);
n /= 10;
}

n = 0;
while (!temp.empty())
{
n = temp.front();
temp.pop();
ans = ans * 10 + n;
}

if (x < 0) //符号处理
ans = -ans;
if (ans > INT_MAX || ans < INT_MIN)
ans = 0;
return (int)ans;
}
};

下面看大神们的最简洁的代码(作者不知):

class Solution {
public:
int reverse(int x) {
long long res = 0;
while(x) {
res = res*10 + x%10;
x /= 10;
}
return (res<INT_MIN || res>INT_MAX) ? 0 : res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 数据结构