题目:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
题目意思很简单,但是需要考虑溢出。
尝试了字符串的解法和纯int数字解,发现后者效率更高,那么笔者是如何判断是否溢出的呢?比如1234567899,正序不溢出,逆序溢出。
做法:先判断位数,位数等于10的话,将逆序得到的结果再逆序,与原先的x进行比较,若不等,则溢出。效率还算比较高的一种判断方法。
解法1:
class Solution {
public:
int reverse(int x) {
if(x==0)
return 0;
int res=x%10;
int Backup_x=x;
x=x/10;
int flag=1;//记录位数
while(x!=0)
{
res=x%10+res*10;
x=x/10;
flag++;
}
//check overflow
if(flag==10&&Check_Reverse(res)!=Backup_x)
{
return 0;
}
return res;
}
private:
int Check_Reverse(int x){
int res=x%10;
x=x/10;
while(x!=0)
{
res=x%10+res*10;
x=x/10;
}
return res;
}
};
解法二:
class Solution {
public:
int reverse(int x) {
if(x==0||abs(x)<0)
return 0;
int flag=x>0?1:-1;
x=abs(x);
// cout<<"x"<<x<<endl;
stringstream ss;
string str;
ss<<x;
ss>>str;
string newstr="";
for(int i=0;i<str.size();i++)
{
newstr=str[i]+newstr;
}
x = atoi(newstr.c_str());
//check overflow
// cout<<check_reverse(x)<<" "<<newstr<<endl;
if(newstr.size()==10&&check_reverse(x)!=newstr)
{
return 0;
}
return flag*x;
}
private:
string check_reverse(int x){
stringstream ss;
string str;
ss<<x;
ss>>str;
return str;
}
};
该方法耗时12ms..比前一个慢了些许。