C# - check against int.MaxValue


  • 0
    public int Reverse(int x) {
        bool neg = x < 0;
        if (neg) x = 0 - x;
        int result = 0;
        while (x > 0)
        {
            int digit = x % 10;
            x = x / 10;
            if (result > (int.MaxValue - digit) / 10) return 0;
            result = result * 10 + digit;
        }
        
        return neg ? 0 - result : result;
    }

Log in to reply
 

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