String类型转int类型

来源:互联网 发布:sql 索引超出数组界限 编辑:程序博客网 时间:2024/05/18 01:43
public class MyAlgTest {

public static int atoi(String str){
      if(str == null || str.length() < 1){
           return 0;
      }
           str = str.trim();
           char flag = '+'; 
           int i = 0;
           if(str.charAt(0) == '-'){
                 flag = '-';
                 i++;
           }else if(str.charAt(0) == '+'){
                 i++;
           }
             double result = 0;
            while(str.length() > i && str.charAt(i) >= '0' && str.charAt(i) <= '9'){
                     result = result * 10 + (str.charAt(i) - '0');
                      i++;
             }
            if(flag == '-'){
                    result = -result;
             }
           if(result > Integer.MAX_VALUE){
                   return Integer.MAX_VALUE;
            }
           if(result < Integer.MIN_VALUE){
                    return Integer.MIN_VALUE;
           }
           return (int)result;
}
}
0 0
原创粉丝点击