8字符串转换整形
注意边界
class Solution {
public int myAtoi(String str) {
char[] chars = str.toCharArray();
int len = chars.length;
int index = 0, res = 0;
// 去空格
while (index < len && chars[index] == ' ') {
index++;
}
// 如果char全为空格,index==len
if (index == len) {
return 0;
}
int flag = 1;
// 遇到+
if (chars[index] == '+') {
index++;
}
// 遇到-
else if (chars[index] == '-') {
flag = -1;
index++;
} else if (!Character.isDigit(chars[index])) {// 非数字
return 0;
}
// 数字
while (index < len && Character.isDigit(chars[index])) {
int temp = chars[index] - '0';
// res*10+temp>Integer.Max_Value
if (res > (Integer.MAX_VALUE-temp) / 10) {
return flag==1?Integer.MAX_VALUE:Integer.MIN_VALUE;
}
res = res * 10 + temp;
index++;
}
return flag * res;
}
}

浙公网安备 33010602011771号