How about this concise solution (Java)


  • 0
    H
    public int reverse(int x) {
        StringBuffer sb = new StringBuffer(Long.toString(Math.abs((long)x)));
        Long data = (x < 0) ? -Long.parseLong(sb.reverse().toString()) : Long.parseLong(sb.reverse().toString());
        return (data > Integer.MAX_VALUE || data < Integer.MIN_VALUE)? 0 : data.intValue();
    }

  • 0
    A

    Even shorter:

    public static int reverse(int x) {
            long abs = Long.parseLong(new StringBuilder(Long.toString(Math.abs((long) x))).reverse().toString());
            if (abs > Integer.MAX_VALUE) abs = 0;
            return  x < 0 ? -(int)abs : (int)abs;
        }

Log in to reply
 

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