My accepted 6 lines of code for Java


  • 0
    Z
    public class ReverseInteger {
        public int reverse(int x) {
            String str = x > 0 ? new StringBuilder(Math.abs(x)+"").reverse().toString() :
                    "-" + new StringBuilder(Math.abs(x)+"").reverse().toString();
            try {
                return Integer.parseInt(str);
            } catch (NumberFormatException e){
                return 0;
            }
        }
    }
    

  • 0
    K

    @zdRan Exception is expensive. If you convert a bunch of integers those cause that exception happen a lot, you will see a significant degrading of performance.


Log in to reply
 

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