C++ 15ms solution int container and sign seperation


  • 2
    C

    Reversal is done in positive integer range. Use the fact that the only negative number that cannot be represented as positive integer is INT_MIN which overflows in positive range.

        int reverse(int x) {
        int sign = 1;
        if (x<0) {
            sign = -1;
            x = -x; // make it positive
            if (x<0) // x was numeric_limits<int>::min() -2^31
                return 0;
        }
        int res = 0;
        while (x) {
            if (res > numeric_limits<int>::max() / 10)
                return 0;
            res = res*10 + x% 10;
            x /= 10;
        }
        return res*sign;
    }

Log in to reply
 

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