本题比较简单,也比较坑爹,
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
题目明确提示了你要考虑反转后溢出的的问题。如果溢出了,返回什么都不合适,那就统一返回一个错误代码吧,return -1吧。这样写提交通过
class Solution {
public:
int reverse(int x) {
int result=0;
bool is_positive=x>0?true:false;
if(!is_positive)
x=-x;
while(x>0){
int add=x-x/10*10;
//std::cout<<"x="<<x<<",add="<<add<<",result="<<result<<std::endl;
result=result*10+add;
x=x/10;
}
if(result<0)
return -1;
if(!is_positive)
result=-result;
return result;
}
};
//if(result<0)
// return -1;
update1:后来看到一个更好的解决溢出办法在这里 http://blog.youkuaiyun.com/stephen_wong/article/details/28779481
update2 : 2014-10-06 简化之前的代码。
因为leetcode没有让人处理溢出,所以这里暂时不处理溢出。(如果要处理,看上面给出的参考链接)。不处理溢出的版本重写后是这样的:
class Solution {
public:
int reverse(int x) {
bool is_pos = x > 0;
x = abs(x);
int result = 0;
while (x >= 1) { //逐个地处理x的个位,十位,百位...
result = result * 10 + x % 10; //注意求个位可以用%,不用像上面那么麻烦。
x = x / 10;
}
if (is_pos) return result;
else return -result;
}
};