LeetCode 007 ReverseInteger

来源:互联网 发布:360云盘程序员 编辑:程序博客网 时间:2024/05/29 04:47
7. Reverse Integer
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?

For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Update (2014-11-10):
Test cases had been added to test the overflow behavior.
class Solution {
public:
    int reverse(int x) {
    }
};
解题思路:
  • 自己的解题思路
因为要考虑溢出情况,所以经典的转换方法不能直接用,需要做点改变。
10000 00003  倒序后变成30000 00001会出现溢出情况。
我的方法是:用个string str_max来记录MAX_INT,则【-MAX_INT, MAX_INT】可以通过转化为【0, MAX_INT】来解决问题。对于MIN_INT直接处理。
题目明确说了,溢出返回0
  • 别人的解题思路
通过用long long 来记录int值,不推荐用long. 这样就可以直接用经典倒序算法直接对int x进行倒序。此方法很巧妙,需突破思维禁锢。
同时,他将正数跟负数一起处理,不需要分情况讨论。
学习收获:
  • 学到一招,小范围数转到大范围数,来防止溢出。
  • 对于已知一个string str;求它的倒序,可以string temp(str.rbegin(), str.rend());
还要更简单的方法?可以直接对它进行倒序?
附件:程序
1、自己的程序:
intreverse(intx)
    {
        if(INT_MIN==x)
        {
            return0;
        }
        intux=(x>0)?x:-x;
        intflag=(x>0)?1:-1;
        inttemp=ux;
        intlen=0;
        while(temp)
        {
            len++;
            temp/=10;
        }
        if(len<10)
        {
            intres=0;
            while(ux)
            {
                res=res*10+ux%10;
                ux/=10;
            }
            returnres*flag;
        }
        else
        {
            stringstr1,str;
            intmax_tem=INT_MAX;
            temp=ux;
            while(temp)
            {
                str1.push_back(temp%10+'0');
                str.push_back(max_tem%10+'0');
                temp/=10;
                max_tem/=10;
            }
            stringstr_max(str.rbegin(),str.rend());
            if(str1>str_max)
            {
                return0;
            }
            else
            {
                intres=0;
                while(ux)
                {
                    res=res*10+ux%10;
                    ux/=10;
                }
                returnres*flag;
            }
        }
    }
2、别人的程序
intreverse(intx)
{
    long long r = 0;
    while(x)r=r*10+x%10,x/=10;
    return(int(r)==r)*r;
}
0 0