Java solution based on StringBuilder without reverse(), using try catch dealing with overflow


  • 0
    C

    I did not know if it is better to use try catch dealing with overflow, could someone tell me?

    public class Solution {
        public int reverse(int x) {
            char c;
            boolean negative=x<0?true:false;
            StringBuilder sb=new StringBuilder(String.valueOf(x));
            int l=sb.length()-1;
            int i=negative?1:0;
            while(i<l){
                c=sb.charAt(i);
                sb.setCharAt(i++,sb.charAt(l));
                sb.setCharAt(l--,c);
            }
            try{
                   if(negative){
                     return -1*Integer.valueOf(sb.substring(1)).intValue();
                   } else{
                     return Integer.valueOf(sb.toString()).intValue();
                   }
           }catch(NumberFormatException e){
                  return 0;  }
        }
    }
    

Log in to reply
 

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