Share my clean accepted C++ Solution without long type or magic number


  • 13
    J
    class Solution {
    public:
        int reverse(int x) {
            if (x == INT_MIN)
                return 0;
            if (x < 0)
                return -reverse(-x);
            
            int rx = 0; // store reversed integer
            while (x != 0) {
                // check overflow
                if (rx > INT_MAX / 10 || 10 * rx > INT_MAX - x % 10) return 0;
                rx = rx * 10 + x % 10;
                x = x / 10;
            }
            return rx;
        }
    };

  • 0
    K

    Why rx > INT_MAX / 10 ? Not rx > INT_MAX..


  • 0
    J

    Because INT_MAX is the maximum integer type INT can represent. Since rx is also of type INT, it is not possible for rx to exceed INT_MAX. Essentially we are checking whether or not
    rx = rx * 10 + x % 10
    will result in overflow.


  • 0
    This post is deleted!

  • 0

    Would you please tell me that why it is rx > INTMAX / 10 || 10 * rx > INTMAX - x % 10 , not just 10 * rx > INT_MAX - x % 10 in the part of checking overflow?


  • 0
    Z

    Because when you just use 10 * rx > INT_MAX - x % 10, if 10 * rx ,it will be overflow while rx become a new num < INTMAX.


  • 0
    S
    This post is deleted!

  • 0
    S

    Nice solution. We do not need the second part of the OR condition. Just rx > INT_MAX / 10 is sufficient to check for overflow.


Log in to reply
 

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