//主要考过滤处理
class Solution {
public int myAtoi(String str) {
if(str==null || str.length()<=0) return 0;
//正负数的最大最小值
int MAX = Integer.MAX_VALUE,MIN=Integer.MIN_VALUE;
int res = 0, index = 0;
//过滤开头空格
while(index < str.length() && str.charAt(index)==' '){
index++;
}
//极端情况全部为空格
if(index == str.length()) return 0;
//取正负号
char firstChar = str.charAt(index);
boolean positive=true;
if(!isDigit(firstChar)){
if(firstChar != '+' && firstChar != '-') return 0;
index++;
//不等于减号就为false,等于就为true
positive = firstChar !='-';
}
int sign = positive ? 1 : -1;
//取每一位在非字符截至末尾
while(index < str.length() && isDigit(str.charAt(index))){
//char字符转为原整数,比如'7' - '0'转为int就是7
int digit = str.charAt(index) - '0';
if(res > 214748364 || res==214748364 && digit > 7){
return MAX;
}
if(res < -214748364 || res==-214748364 && -digit < -8){
return MIN;
}
res = res * 10 + sign * (digit);
index++;
}
return res;
}
//判断是否是数字
public boolean isDigit(char c){
return c >='0' && c<='9';
}
}
题解过程:
" 42" => 需要去掉前导空格;
" -42" => 需要判断第 1 个字符为 + 和 - 的情况
" 982 With Word" => 判断是否是数字
"With Word 982 " => 在遇到第 1 个不是数字的字符的情况下,转换停止,退出循环
"8456465456465" => 如果转换以后的数字超过了 int 类型的范围,返回相应的数。
时间复杂度:O(n)
空间复杂度:O(1)