public static int myAtoi(String str) {
if(str == null || str.length() < 1) {
return 0;
}
int len = str.length();
double maxDou = 0;
boolean isPositive = true;
int find = -1;
int place1 = str.lastIndexOf('-');
int place2 = str.lastIndexOf('+');
if(place1 > place2) {
isPositive = false;
maxDou = Integer.MAX_VALUE*1.0 + 1;
}else {
maxDou = Integer.MAX_VALUE*1.0;
}
int resInt = 0;
double tmpDou = 0;
int i = 0;
boolean overflag =false;
for(i = 0 ;i < len; i++) {
if(resInt != 0) {
find =1;
}
char c = str.charAt(i);
if(((c == '+' || c == '-') && find == -1) || (c == '0' && resInt == 0) || (c ==' ' && find == -1)) {
if((c == '+' || c == '-') && find == -1) {
find = 1;
}
continue;
}else if(c >= '0' && c <= '9') {
tmpDou = tmpDou*10 + char2num(c);
if(tmpDou > maxDou) {
resInt = isPositive?Integer.MAX_VALUE:Integer.MIN_VALUE;
overflag = true;
break;
}
resInt = resInt*10 + char2num(c);
}else{
break;
}
}
return overflag ?resInt:(isPositive?resInt:-resInt);
}
public static int char2num(char c) {
int i=0;
switch(c) {
case '0' :
i=0;
break;
case '1' :
i=1;
break;
case '2' :
i=2;
break;
case '3' :
i=3;
break;
case '4' :
i=4;
break;
case '5' :
i=5;
break;
case '6' :
i=6;
break;
case '7' :
i=7;
break;
case '8' :
i=8;
break;
case '9' :
i=9;
break;
}
return i;
}
8. String to Integer (atoi)
最新推荐文章于 2020-04-03 12:34:44 发布