LeetCode:Reverse Integer

Posted 翎飞蝶舞

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode:Reverse Integer相关的知识,希望对你有一定的参考价值。

7. Reverse Integer

 
Total Accepted: 126996 Total Submissions: 538523 Difficulty: Easy

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

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.

 

 

    用各数位与int边界值比大小的方式,来确定是否越界。

class Solution {
public:
    int reverse(int x) {
        int neg=0;
        if (x<0)
        {
            neg=1;
            x=0-x;
        }
        int y=0;
        while(1)
        {
            int tmp1=x/10;
            int tmp2=x%10;
            if(neg!=1)
            {
                if(y>214748364)
                {
                    y=0;
                    break;
                }
                else if(y==214748364 && tmp2>7)
                {
                    y=0;
                    break;
                }
            }
            else
            {
                if(y>214748364)
                {
                    y=0;
                    break;
                }
                else if(y==214748364 && tmp2>8)
                {
                    y=0;
                    break;
                }
            }
            y=y*10+tmp2;
            x=tmp1;
            if(x==0)
                break;
        }
        if(neg==1)
            y=0-y;
        return y;
    }
};

        但是存在问题:若x=-2147483648,在第一步取反的时候就已经越界了。所以改用long long类型忽略越界的情况计算翻转值,最后再判断是否越界。

class Solution {
public:
    int reverse(int x) {
        int neg=0;
        long int y=0,tx=x;
        if (tx<0)
        {
            neg=1;
            tx=0-tx;
        }
      
        while(1)
        {
            int tmp1=tx/10;
            int tmp2=tx%10;
         
            y=y*10+tmp2;
            tx=tmp1;
            if(tx==0)
                break;
        }
        
        if(neg==1)
            y=0-y;
        if(y>INT_MAX || y<INT_MIN)
            return 0;
        return y;
    }
};

 

以上是关于LeetCode:Reverse Integer的主要内容,如果未能解决你的问题,请参考以下文章

leetcode : reverse integer

LeetCode--Reverse Integer

[Leetcode] reverse integer 反转整数

[LeetCode]-algorithms-Reverse Integer

LeetCode---------Reverse Integer解法

LeetCode Reverse Integer