Solution in Java.

  • 0

    Solution is based on StringBuilder().reverse() method. If the reversed integer overflows, Integer.parseInt() throws NumberFormatException - in this case returns 0.

            int abs = (int) Math.abs(x);
            String reversedStringResult = new StringBuilder(""+abs).reverse().toString();
                return (x == abs) ?
                    Integer.parseInt(reversedStringResult) : 
                    Integer.parseInt("-" + reversedStringResult);
            }catch(Exception e){ // ~10ms faster than check for NumberFormatException
                return 0;

Log in to reply

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