String to Integer (atoi)

来源:互联网 发布:制作cg动画软件 编辑:程序博客网 时间:2024/05/13 17:56

ref http://www.cnblogs.com/springfor/p/3896499.html



public class Solution {

    public int atoi(String str) {
        if(str==null || str.length()<=0) return 0;
        
        str = str.trim();
        
        int i=0, flag = 1;
        
        if(str.charAt(i)=='-') {
            flag=-1;
            i++;
        }else if(str.charAt(i)=='+') {
             i++;
        }          // 注意这里如果不处理第一位,则会把 +/- 当成数字被处理

            
        int res = 0;
        
        while(i<str.length() && str.charAt(i) >='0' && str.charAt(i) <='9'){
            
            if( Integer.MAX_VALUE/10<res || (Integer.MAX_VALUE/10== res && Integer.MAX_VALUE%10 < str.charAt(i)-'0'))
                return flag<0? Integer.MIN_VALUE: Integer.MAX_VALUE;
            
            res = res*10 + str.charAt(i)-'0';
            i++;
        }
        
        return flag <0? -res : res;
    }
}
0 0
原创粉丝点击