Solution in Java (with negativ, overflow handling and StringBuilder)


  • 0
    O
     public int reverse( int x ) {
                try {
                    StringBuilder stringBuilder = new StringBuilder();
                    if (x >= 0) {
                        while(x!=0){
                        stringBuilder.append(x % 10);
                        x /= 10; }
                     }
                    else {
                        x = Math.abs(x);
                        stringBuilder.append( "-" );
                        while(x != 0){
                            stringBuilder.append(x % 10);
                            x /= 10;
                        }
                    }
                    return Integer.parseInt( stringBuilder.toString() );
               } catch  ( Exception e ) {
                    return 0;
                }
            }
    

Log in to reply
 

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