My Java Solution with StringBuilder


  • 0
    X

    Check if the int is negative first, if negative, discard the sign first and reverse the digit, adding the negative sign in the end.
    Using exception handling to deal with integer overflow.

        public int reverse(int x) {
            boolean neg = false;
            if (x < 0) {
                neg = !neg;
                x = -x;
            }
            String string = String.valueOf(x);
            StringBuilder builder = new StringBuilder(string);
            System.out.println(builder);
            builder.reverse();
            string = new String(builder);
            Integer result;
            try {
                result = Integer.valueOf(string);
            } catch (Exception e) {
                return 0;
            }     
            return neg?-result:result;
        }
    }
    

Log in to reply
 

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