Clean and easy to understand Java solution


  • 0
    J
        public int reverse(int x) {
            
            boolean negative = false;
            String number = String.valueOf(x);
            String newNumber = "";
            
            if(number.charAt(0) == '-'){
                
                negative = true;
                number = number.replace("-", "");
                
            }
            
            for(int i = number.length() - 1; i >= 0; i--){
                
                newNumber += String.valueOf(number.charAt(i));
                
            }
            
            try{
                
                x = Integer.parseInt(newNumber);
                
            } catch(Exception e){
                
                return 0;
                
            }
            
            if(negative){
                
                x *= -1;
            
            }
            
            return x;
        }
        
    }
    

Log in to reply
 

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