Day34(字符串到整数)
class Solution {
public int myAtoi(String str) {
char[] chars = str.toCharArray();
int n = chars.length;
int cur = 0;
//去掉前导空格
while(cur<n && chars[cur]==' '){
cur++;
}
if(cur==n){
return 0;
}
boolean negative = false;
if(chars[cur]=='-'){
negative = true;
cur++;
}else if(chars[cur]=='+'){
cur++;
}else if(!Character.isDigit(chars[cur])){
return 0;
}
int ans = 0;
int digit = 0;
while(cur<n && Character.isDigit(chars[cur])){
digit = chars[cur]-'0';
if(ans>(Integer.MAX_VALUE-digit)/10){ //保证不溢出
return ans = negative? Integer.MIN_VALUE:Integer.MAX_VALUE;
}
ans = ans*10+digit;
cur++;
}
return negative?-ans:ans;
}
}