您的位置:首页 > 其它

Reverse Integer [LeetCode]

2013-11-03 06:11 411 查看
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?

Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).

Solution: be careful about corner case, like INT_MIN, 0, and -INT_MIN is not equals to INT_MAX. Here is the definition of them in limits.h

#define INT_MIN     (-2147483647 - 1) /* minimum (signed) int value */
#define INT_MAX       2147483647    /* maximum (signed) int value */


int reversePostiveInt(int x){
vector<int> digits;
while(true) {
if(x < 10 ){
digits.push_back(x);
break;
}else {
int remainder = x % 10;
int quotient = x / 10;
digits.push_back(remainder);
x = quotient;
}
}
// reverse output
long long int ret = 0;
for(int i = 0; i < digits.size(); i ++) {
ret = ret * 10 + digits[i];
if(ret > INT_MAX){
ret = INT_MAX;
break;
}
}
return (int) ret;
}

int reverse(int x) {
if(x == 0 )
return 0;
if(x > 0) {
return reversePostiveInt(x);
}else if( x == INT_MIN){
//overflow
return INT_MIN;
}else if ( x > INT_MIN) {
return -reversePostiveInt(-x);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: