您的位置:首页 > 其它

LEETCODE: Reverse Integer

2014-12-10 17:17 387 查看
这个题目比较简单! 但是我发现居然没有通过测试,这里就有一个问题。

下面的代码是copy的,当然我自己写的思路和它是一样的。

class Solution {
public:
int reverse(int x) {
int res = 0;

while (x != 0) {       // don't care positive or negetive
res = res * 10 + x % 10;   // get lowest digit then multi 10
x /= 10;
}

return res;
}
};


当然现在有个错误的结果,因为溢出了。


Submission Result: Wrong Answer

Input:1534236469
Output:1056389759
Expected:0
所以,要考虑溢出。

int reverse(int x) {
int res = 0;
int highlimit = 0x7fffffff / 10;
int lowlimit = int(0x80000000) / 10;

while (x != 0) {       // don't care positive or negetive
if(res > highlimit || res < lowlimit)
return 0;

res = res * 10 + x % 10;   // get lowest digit then multi 10

x /= 10;
}

return res;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LEETCODE 算法