Solution in Java


  • 0
    S
    class Solution {
        public int reverse(int x) {
            try{
            boolean neg=false;
            if(x<0){
                x=x*(-1);
                neg=true;
            }
            String str=String.valueOf(x);
            //System.out.println("Converted integer:"+str);
            char arr[]=new char[str.length()];
            int j=0;
            for(int i=str.length()-1;i>=0;i--){
                arr[j]=str.charAt(i);
                j++;
            }
            String str1=String.valueOf(arr);
            int newnum=Integer.parseInt(str1);
            //System.out.println("reversed num:"+newnum);
            if(neg){
                newnum=newnum*(-1);
            }
            return newnum;
            }
            catch(Exception e){
                System.out.println("Error:"+e);
                return 0;
            }
        }
    }
    

Log in to reply
 

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