public static int myAtoi(String s) {
if(s == null || "".equals(s)){
return 0;
}
// 去掉前置空格
String trimStr = s.trim();
// 使用long类型,为了容易判断当前数值是否超过了Integer的范围,
long a = 0;
// 符号位
Integer sign = 1;
// 字符串下标
Integer index = 0;
for (char c : trimStr.toCharArray()) {
// 获取下标
if(index == 0 && ('-' == c || '+' == c)){
// 判断首位是否是符号位
sign = '-' == c ? -1:1;
}else {
// 判读是否是数字
if(c >= '0' && c <= '9'){
int s1 = c-'0';
// 符号位不参与计算,只是为了拼接数字。
a = a*10+s1;
// 当数值超过指定值时,返回最大的值
if(a*sign >= 2147483647){
return 2147483647;
}
if(a*sign <= -2147483648){
return -2147483648;
}
}else {
return (int) a*sign;
}
}
index ++;
}
return (int) a*sign;
}