您的位置:首页 > 其它

【leetcode】7. Reverse Integer

2016-07-07 22:38 274 查看
一、题目描述

Reverse digits of an integer.

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

click to show spoilers.
Have you thought about this?
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.
Update (2014-11-10):

Test cases had been added to test the overflow behavior.

题目解读:将数字反转,注意溢出的情况,溢出的时候返回0
思路:反转比较简单,特别注意溢出的情况。int型最大值INT_MAX和最小值INT_MIN,头文件是<limits.h>。注意result最好定义为long,定义为int后面为报错,因为会有溢出的数。
c++代码(8ms,48.11%)

class Solution {
public:
int reverse(int x) {
long result=0;
while(x){
result = result*10 + x%10;
x=x/10;
}//while
//防止溢出
if(result > INT_MAX || result < INT_MIN)
{
result = 0;
}
return result;
}
};


其他代码:

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