Very Easy to Understand Java Solution


  • 0
    P
    public class Solution {
        public int myAtoi(String str) {
            str=str.trim();
            boolean flag=false;
            if(str.equals("")||str==null) return 0;
            StringBuffer sb=new StringBuffer();
            String sign="+-";
            String digit="0123456789";
            if(sign.indexOf(str.charAt(0))!=-1) 
                flag=str.charAt(0)=='-';
            else if(digit.indexOf(str.charAt(0))!=-1)
                sb.append(str.charAt(0));
            else return 0;
            for(int i=1; i<str.length(); ++i) {
                if(digit.indexOf(str.charAt(i))!=-1) sb.append(str.charAt(i));
                else {
                    break;
                }
            } 
            if(sb.length()==0) return 0;
            if(sb.length()>18) return flag?Integer.MIN_VALUE:Integer.MAX_VALUE; 
            long res=Long.parseLong(sb.toString());
            if(!flag&&res>Integer.MAX_VALUE) return Integer.MAX_VALUE;
            else if(flag&&res>Integer.MAX_VALUE) return Integer.MIN_VALUE;
            else return flag?(int)(-1*res):(int)res; 
        }
    }

  • 0
    Q

    you used long.pareselong to conver stringbuffer to long. Shouldn't we calculation string to integer


  • 0
    P

    that might be overflow because the string could be very large number.


Log in to reply
 

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