Share my C++ solution


  • 1
    V

    use long long int

    class Solution {
    public:
        int reverse(int x) {
            if (x == 0) return x;
            int sign = 1;
            long long int sum = 0;
            if (x < 0) 
                x = -x, sign = -1;
            
            while (x > 0)
            {
                sum = sum * 10 + (x % 10);
                x /= 10;
                
                if (sum * sign > INT_MAX || sum * sign < INT_MIN)
                    return 0;
            }
            
            return (int)sum * sign;
        }
    };
    

    without long long int

    class Solution {
    public:
        int reverse(int x) {
            if (x == 0) return x;
            int sum = 0, low = 0, sign = 1;
            if (x < 0) 
                x = -x, sign = -1;
            
            while (x > 0)
            {
                low = x % 10;
                if ((INT_MAX - low) / 10 < sum)
                    return 0;
                sum = sum * 10 + low;
                x /= 10;
    
            }
            
            return sign * sum;
        }
    };

  • 0
    S

    Is there some coincidence?
    For the test case:-2147483648,statement "x = -x" is invalid(After execution,its value is also -2147483648).But for the value of sum is 0,the result is "return sign * 0".This test case is absolutely perfectly avoided.


  • 0
    V

    This is no coincidence,for x = -2147483648,the result of x = -x remains -2147483648,then it won't execution the loop,so it has no effect.


  • 0
    V

    You consider it very comprehensive,I also spend some time on thinking how to handle the overflow.


  • 0
    S

    I thought for a long time.I think perhaps your solution is the most concise.The best way to solve the overflow above is to avoid it.:-p


  • 0
    V

    "The best way to solve the overflow above is to avoid it",Fair enough.


  • 0
    Z
    This post is deleted!

Log in to reply
 

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