Java solution for Reverse Integer


  • 0
    K
    public int reverse(int x) {
            if (x == 0 || x == Integer.MIN_VALUE) {
                return 0;
            }
            boolean positive = x > 0;
            int result = 0;
            //When x!=Integer.MIN_VALUE, -x doesn't overflow
            x = positive ? x : -x;
            while (x > 0) {
                int r = x % 10;
                //overflow check
                if ((result == Integer.MAX_VALUE / 10 && r > Integer.MAX_VALUE % 10) || (result > Integer.MAX_VALUE / 10)) {
                    return 0;
                }
                result = (result * 10 + r);
                x = x / 10;
            }
            return positive ? result : -result;
        }
    

Log in to reply
 

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