8.字符串转换整数(atoi)
![image-20231120200911993](https://i-blog.csdnimg.cn/blog_migrate/bb1139fd61ff8817bffb8ece03e2fb13.png)
class Solution {
public int myAtoi(String s) {
int sign = 1;
int n = s.length();
int index = 0,res = 0;
while(index < n && s.charAt(index) == ' '){
index++;
}
if(index < n && (s.charAt(index)=='+' || s.charAt(index)=='-')){
sign = s.charAt(index++) == '+'? 1:-1;
}
while(index < n && Character.isDigit(s.charAt(index))){
int digit = s.charAt(index)- '0';
if(res > (Integer.MAX_VALUE - digit) / 10){
return sign == 1 ? Integer.MAX_VALUE:Integer.MIN_VALUE;
}
res = res * 10 + digit;
++index;
}
return res * sign;
}
}