a string way to solve such problems


  • 0
    B
    class Solution {
        public int reverse(int x) {
            StringBuilder sb = new StringBuilder();
            String s = String.valueOf(x);
            // String s1 = Integer.toString(x);
            // String s2 = ""+x;
            if(s.charAt(0)=='-'){
                sb.append('-');
                for(int i=s.length()-1;i>0;i--)
                    sb.append(s.charAt(i));
            }
            else{
                for(int i=s.length()-1;i>=0;i--)
                    sb.append(s.charAt(i));
            }
            // System.out.println(sb);
            // return Integer.valueOf(sb.toString());
            try{
                return  Integer.parseInt(sb.toString());
            }catch (NumberFormatException e){
                System.out.println(e);
            }
            return 0;     
        }
    }
    

Log in to reply
 

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