My Java Solution


  • 0
    R
        public int reverse(int x) {
            int num = 0;
            // store the sign and remove it if negative
            int sign = x < 0 ? -1 : 1;
            x = x < 0 ? x * -1 : x;
            while (x > 0) {
                if (Integer.MAX_VALUE / 10 < num || (Integer.MAX_VALUE / 10 == num && x % 10 > 7)) {
                    // integer min value ends in 8
                    if (Integer.MAX_VALUE / 10 < num || (sign == 1 || num % 10 > 8)) {
                        return 0;
                    }
                }
                num = (num * 10) + (x % 10);
                x = x / 10;
            }
            return num * sign;
        }
    

Log in to reply
 

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