Understandable c++ solution handles overflow


  • 3
    L
    class Solution {
    public:
        int reverse(int x) {
            // -x overflows
            if (x < 0 && -x < 0) return 0;
            
            if (x < 0) return -reverse(-x);
            
            int reversed = 0;
            int remains = x;
    
            while (remains > 0) {
                int d = remains % 10;
                // reversed overflows
                if (reversed > (INT_MAX-d)/10) return 0;
                reversed = reversed * 10 + d;
                remains = remains / 10;
            }
            return reversed;
        }
    };

  • 0
    W

    Hi, your code is really concise. However, I don't understand this line :
    if (x < 0 && -x < 0) return 0;
    what do you mean by "-x overflows", the input value is negative and overflow?
    Could you give me some explain in detail? Thank you.


Log in to reply
 

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