直接转为数组遍历判断
把字符串转换成整数
http://www.nowcoder.com/questionTerminal/1277c681251b4372bdef344468e4f26e
public int StrToInt(String str) { if(str == null || str.length() == 0)return 0; char[] arr = str.toCharArray(); boolean negative = true; int res = 0; for(int i = 0;i<arr.length;i++){ if(arr[i]>='0' && arr[i]<='9'){ //判断溢出 int cur = Character.digit(arr[i],10); if(negative&& (res > Integer.MAX_VALUE/10 || res == Integer.MAX_VALUE/10 && cur >7)){ return 0; } if(!negative&& (res > Integer.MAX_VALUE/10 || res == Integer.MAX_VALUE/10 && cur >8)){ return 0; } res = res*10 + cur; }else if(arr[i] =='+'){ negative = true; }else if(arr[i] == '-'){ negative = false; }else{ return 0; } } return negative ? res : -res; }