public static int myAtoi(String str) {
if (str.length() == 0)
return 0;
//记录值
int num = 0;
//标记是正是负
int flag = 0;
/*
* 判断是否含有空格
*/
if (str.charAt(0) == ' ') {
for (int i = 1; i < str.length(); i++) {
if (str.charAt(i) != ' ') {
str = str.substring(i);
break;
}
}
}
/*
* 累加为整数
*/
for (int i = 0; i < str.length(); i++) {
if(i == 0 &&str.charAt(i) == '-'){
flag = 1;
num = 0;
continue;
}
if( i == 0 &&str.charAt(i) == '+'){
num = 0;
continue;
}
if (str.charAt(i) - '0' > 9 ||str.charAt(i) - '0' < 0) {
break;
}
int p = str.charAt(i) - '0';
if(flag == 1)
p = -p;
/*
* 注意点三 判断是否超出int范围 ,可以用long来做
* 注意long 初始化是long l = 0l,而不是0
* ssssl = (long)num * 10 +(long)p ;这句话伤我千百遍
*/
long ssssl = 0l;
ssssl = (long)num * 10 +(long)p ;
if(ssssl > 2147483647){
num = 2147483647 ;
return num;
}else if(ssssl < -2147483648){
num = -2147483648;
return num;
}
else
num = num * 10 + p;
}
return num;
}