2015年7月2日星期四

lintcode @54 String to Integer(atoi) Java

1. trim string.
2. loop until . other character.
    judge if bigger than Integer.MAX_VALUE or smaller than Integer.MIN_VALUE

public class Solution {
    /**
     * @param str: A string
     * @return An integer
     */
    public int atoi(String str) {
        if(str==null)
            return 0;
        str=str.trim();
        int i=0;
        boolean neg=false;
        if(str.length()==0)
            return 0;
        if(str.charAt(0)=='-')
        {
            neg=true;
            i++;
        }else if(str.charAt(0)=='+')
            i++;
        int res=0;
        while(i<str.length()){
            char c= str.charAt(i);
            if(c=='.'){
                if(i-1<0 || str.charAt(i-1)>'9'|| str.charAt(i-1)<'0')
                    return 0;
                break;
            }else if( c>'9'|| c<'0')
                break;
            if(!neg && res>(Integer.MAX_VALUE -  c-'0')/10)
                return Integer.MAX_VALUE;
            else if(neg && res > (Integer.MIN_VALUE +  c-'0')/10 *-1 )
                return Integer.MIN_VALUE;
            else{
                res= res*10+ c-'0';
            }
            i++;
        }
        return neg? -res:res;
    }
}

没有评论:

发表评论