Share my solution with dealing with overflow correctly


  • -1
    S
    int reverse(int x) {
            static const int MAX = (int)((unsigned)~0 >> 1);
            static const int MIN = -(int)((unsigned)~0 >> 1) - 1;
            static const int MAX_DIV = (int)((unsigned)~0 >> 1) / 10;
            static const int MIN_DIV = (int)((((unsigned)~0 >> 1) + 1) / 10);
            static const int MAX_R = (int)((unsigned)~0 >> 1) % 10;    
            static const int MIN_R = (int)((((unsigned)~0 >> 1) + 1) % 10); 
        
            int sign = 1;
            if (x < 0) {
                if (x <= MIN) return 0;
                sign = -1;
                x = sign * x;
            }
            
            int y = 0, mode = 0;
            while (x) {
                mode = x % 10;
                
                // overflow
                if (sign > 0 && (y > MAX_DIV || (y == MAX_DIV && mode >= MAX_R)))
                    return 0;
                if (sign < 0 && (y > MIN_DIV || (y == MIN_DIV && mode >= MIN_R)))
                    return 0;
                
                y = 10 * y + mode;
                x = x / 10;
            }
            
            return sign * y;
        }

Log in to reply
 

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