思路
1.遍歷字符串酵颁,當(dāng)字符不符合條件時(shí)結(jié)束
2.處理特殊情況
3.組合數(shù)字
代碼
int myAtoi(char* str) {
int str_len = strlen(str);
int i, flag = 0;
int result = 0, cur = 0;
char c;
for (i = 0; i < str_len; i++) {
c = str[I];
//標(biāo)示符號(hào)和是否開(kāi)始數(shù)字
if (c == '+' && !flag ) {
flag = 1;
continue;
}
else if (c == '-' && !flag) {
flag = -1;
continue;
}
else if (c >= '0' && c <= '9') {
if (flag != -1) {
flag = 1;
}
//記錄數(shù)字
cur = result * 10 + (c - '0');
}
//處理空格和結(jié)束
else if (c == ' ' && !flag){
continue;
}
else {
break;
}
//越界判斷
if ((cur - c + '0') / 10 != result || cur < 0) {
if (flag == 1) {
return INT_MAX;
}
else if (flag == -1) {
return INT_MIN;
}
}
else {
result = cur;
}
}
//負(fù)數(shù)
if (flag == -1) {
result = 0 - result;
}
return result;
}