Java StringBuilder Solution


  • 0
    V

    Hey guys, I'm a bit new to programming and I used the Java StringBuilder for my accepted solution. It worked, but I'm not sure of the efficiency? Any input would be appreciated!

    public int reverse(int x) {
            boolean positive = true;
            if(x < 0) {
                positive = false;
            }
            
            StringBuilder number = new StringBuilder();
            if(positive) {
                number.append(x);
                number.reverse();
                try {
                    return Integer.parseInt(number.toString());
                } catch(NumberFormatException e) {
                    return 0;
                }
            } else {
                x = x*-1;
                number.append(x);
                number.reverse();
                try {
                    return Integer.parseInt("-" + number.toString());
                } 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.