Considering Number as a String (Java)


  • 0
    N
     public int reverse(int x) {
            int reverse = 0;
            boolean neg = false;
            if (x < 0){
                neg = true;
            }
            x = Math.abs(x);
            String original = Integer.toString(x);
            String rev = new StringBuilder(original).reverse().toString();
            try{
                reverse = Integer.parseInt(rev);
            }
            catch(NumberFormatException e){
                return 0;
            }
            return neg? -reverse : reverse;
            
        }
    

Log in to reply
 

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