Java StringBuilder comparison solution

  • 0

    This solution essentially converts the int to string, makes use of the stringbuilder library where it reverses the string then converts it back to an int. A little unnecessary but its a different solution. Not counting the library methods it is O(1)

    public int reverse(int x) {
            int neg = 1, temp =0;
            if(x < 0){
                x *= -1;
                neg = -1;
            String pre = Integer.toString(x);
            StringBuilder sb = new StringBuilder(pre);
            String post = sb.reverse().toString();
            if(pre.charAt(0)!= post.charAt(post.length()-1)) return 0;
                temp = Integer.parseInt(post);
            catch(NumberFormatException e){
                return 0;
            return temp * neg;

Log in to reply

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