A Solution in Java


  • 0
    L

    Solution:
    Parse the number to StringBuilder and use the StringBuilder.reverse() to get the result.
    Catch and handle NumberFormatException when result overflows.

            try {
                StringBuilder xToStringBuilder = new StringBuilder(new Integer(x).toString());
                xToStringBuilder = xToStringBuilder.reverse();
                // if x contains "-"
                int index = xToStringBuilder.indexOf("-");
                if (-1 != index) {
                    xToStringBuilder.deleteCharAt(index);
                    xToStringBuilder.insert(0, "-");
                }
                int result = Integer.parseInt(xToStringBuilder.toString());
                return result;
            } catch (NumberFormatException e) {
            }
            return 0;
    

Log in to reply
 

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