Easy Solution. C++


  • 2
    N
    class Solution {
    public:
        int reverse(int x) {
            int flag=0;
            if(x<0)
            {
                x=-x;
                flag=1;
            }
            long long int ans=0;
            while(x>0)
            {
                ans=ans*10+(x%10);
                x/=10;
            }
            if(ans>INT_MAX)return 0;
            if(flag==1)ans=-ans;
            return ans;
        }
    };

  • 1

    You are absolutely right.
    But I cannot understand, if x is INT_MIN, then x = -x would overflow?
    But your solution passes the test case.
    How could this happen?


  • 0
    N

    Yes you are right....I didn't handle that part.....But it some how passes the testcases.....here can be a solution.:

    class Solution {
    public:
        int reverse(int x) {
            int flag=0;
            long long int xx=x;
            if(xx<0)
            {
                xx=-xx;
                flag=1;
            }
            long long int ans=0;
            while(xx>0)
            {
                ans=ans*10+(xx%10);
                xx/=10;
            }
            if(ans>INT_MAX)return 0;
            if(flag==1)ans=-ans;
            return ans;
        }
    };

  • 0

    But since |INT_MIN| > |INT_MAX| suppose that ans is |INT_MIN| and flag is 1, you will return 0, but actually it is in the valid range, right?


  • 0
    N

    Yes you are right. That is a great corner case! But the answer can never be INT_MIN. For the value to be INT_MIN the input should be -8463847412. Which is not valid. That's why checking with INT_MAX gives the correct answer.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.