Java solution without loop in code


  • 0
    P
    class Solution {
        public int reverse(int x) {
            
            String num=Integer.toString(x);
            char[] charArray = num.toCharArray();
            String reverse;
            int sol;
            
            if(charArray[0]=='-'){
                char[] array2 = Arrays.copyOfRange(charArray, 1, charArray.length);
                reverse=new StringBuilder(new String(array2)).reverse().toString();
            try {   
                   sol=Integer.parseInt(reverse);
                return -sol;
             } catch (NumberFormatException nfe) {
                    return 0;
                 }  
            }else{
                reverse=new StringBuilder(new String(charArray)).reverse().toString();
                 try {   
                   sol=Integer.parseInt(reverse);
                return sol;
             } catch (NumberFormatException nfe) {
                    return 0;
                 } 
            }
        }
    }
    

Log in to reply
 

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