Reverse Integer
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
解题思路:
这道题比较简单,需要注意的就是要考虑int类型翻转之后,可能会溢出,若溢出,则返回0。先用一个long long类型来存储结果,然后转化成int类型,若数值不变,则没有溢出,若数值变了,则溢出了。
class Solution {
public:
int reverse(int x) {
int sign = 1;
if(x<0){
x=-x;
sign=-1;
}
long long tempResult = 0;
while(x!=0){
tempResult *= 10;
tempResult += x%10;
x /= 10;
}
tempResult = tempResult*sign;
int result = (int)tempResult;
if(result!=tempResult){
result=0;
}
return result;
}
};原文地址:http://blog.csdn.net/kangrydotnet/article/details/45096353