8. String to Integer (atoi)

public class Solution {
    public int myAtoi(String str) {
        str=str.trim();
        int size=str.length();
        if(str==null||size==0)
            return 0;
        double res=0;
        boolean isPositive=true;
        for(int i=0;i<size;i++)
        {
            if(i==0&&(str.charAt(i)=='+'||str.charAt(i)=='-'))
            {
                if(str.charAt(i)=='-')
                    isPositive=false;
            }
            else
            {
                if(str.charAt(i)>='0'&&str.charAt(i)<='9')
                {
                    res*=10;
                    res+=str.charAt(i)-'0';
                }
                else
                    break;
            }
        }
        if(isPositive==false)
            res=0-res;
        if (res > Integer.MAX_VALUE)
            return Integer.MAX_VALUE;
     
        if (res < Integer.MIN_VALUE)
            return Integer.MIN_VALUE;
        return (int)res;
    }
}

 

posted @ 2016-08-03 21:30  阿怪123  阅读(127)  评论(0编辑  收藏  举报