这题整的整的挺玄乎的,不过用例还是不够刁钻,这里说的不够刁钻体现在溢出这里。
需要考虑的点:
1.去掉空格
2.前置就是有错也不管,来到第一个数字处开始计算
3.从数字开始之后,到另一个字母或者结尾就截止
public int atoi(String str) {
//-000001
//-000000
//-001000,前0省略,后0不能省
if (str == null || str.length() == 0) return 0;
str = str.replaceAll(" ", "");
char[] cs = str.toCharArray();
boolean isPositive = cs[0] != '-';
int start = isNumber(cs[0]) ? 0 : 1;
int n = str.length();
//找到第一个数字所在
while (start < n && !isNumber(cs[start])) {
start++;
}
//找到正确数字字符串的结尾
int end = start + 1;
while (end < n && isNumber(cs[end])) {
end++;
}
int res = 0;
for (int i = start; i < end; i++) {
if(Integer.MAX_VALUE/10<res){
return isPositive?Integer.MAX_VALUE:Integer.MIN_VALUE;
}//严谨一点需要处理等于的情况,具体就是看当前加入这个是否超过了7,8(这里的7,8是最值的结尾)
res = res*10 + (cs[i] - '0');
}
return isPositive ? res : -res;
}
private boolean isNumber(char c) {
return c - '0' >= 0 && c - '0' <= 9;
} 
京公网安备 11010502036488号