Share my java solution


  • 0
    X
    public class Solution {
        public int atoi(String str) {
            str=str.trim();
            
            int length=str.length();
            if(length==0) return 0;
            
            boolean isNegative=false;
            int i=0;
            if(str.charAt(0)=='-') {isNegative=true;i++;}
            else if(str.charAt(0)=='+'){isNegative=false;i++;}
            
            ArrayList list=new ArrayList();
            for(;i<length;i++){
                if((byte)str.charAt(i)>=(byte)'0' && (byte)str.charAt(i)<=(byte)'9'){
                   list.add((byte)str.charAt(i)-(byte)'0');
                }
                else break;
            }
            
            int intLength=list.size();
            int result=0;
            for(int j=0;j<intLength;j++){
                if(!isNegative){
                     int value=(int)Math.pow(10,intLength-1-j)*((Integer)list.get(j));
                     if(value<0) return Integer.MAX_VALUE;
                     result+=value;
                     if(result<0) return Integer.MAX_VALUE;
                }
                else{
                     int value=(int)Math.pow(10,intLength-1-j)*((Integer)list.get(j));
                     if(value<0) return Integer.MIN_VALUE;
                     result-=value;
                     if(result>0) return Integer.MIN_VALUE;
                }
            }
            
            return result;
        }
    }

Log in to reply
 

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