Reverse Integer

First time:

class Solution {
public:
    int reverse(int x) {
	string str=to_string((long long)fabs((double)x));
	int len=str.length();
	for(int i=0,j=len-1;i<=j;i++,j--)
	{
		swap(str[i],str[j]);
	}
	if(x<0)
	{
		return atoi(str.c_str())*(-1);
	}
	else
	{
		return atoi(str.c_str());
	}
}
};

 转为字符串进行处理,结果出现错误结果:                        

Input: 1534236469
Output: 1056389759
Expected: 0

 int型的最大值为2147483647,发生溢出,输出结果不可预料,因此需要进行处理。

Second time:

class Solution {
public:
    int reverse(int x) {
        bool flag=false;
       if(x<0)
       {
           x*=-1;
           flag=true;
       }
       int res=0;
       while(x)
       {
           int digit=x%10;
           if(res!=0)
           {
               if((INT_MAX-digit)/res<10)
               return 0;
               if(-10<(INT_MIN+digit)/res)
               return 0;
           }
           res=res*10+digit;
           x/=10;
       }
       if(flag&&res>0)
       res*=-1;
       return res;
}
};

 

posted @ 2015-04-08 23:14  zhanghui_dut  阅读(94)  评论(0)    收藏  举报