C solution that avoids the overflow


  • 0
    V

    To avoid using long long, instead of (product * 10 > INT_MAX, check if prod > INTMAX/10). In other words, avoid the overflow instead of catching the overflow.

    int reverse(int x) {
        int y = 0;
        while (x) {
            if (y > INT_MAX/10 || y < INT_MIN/10) return 0;
            y = y*10 + x%10;
            x/=10;
        }
        return y;
    }
    

Log in to reply
 

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