atoi()函数实现
实现atoi()函数,在出错时返回0;
1 int atoi(const char *str) 2 { 3 if((str == NULL) || (strlen(str) == 0)) { 4 return 0; 5 } 6 7 int value = 0; 8 int sign = 0; 9 int index = 0; 10 int minMark = 0; 11 const int MAX = 2147483647; 12 const int MIN = -2147483648; 13 while(str[index] != '\0') { 14 char c = str[index]; 15 if((c == '+') || (c == '-')) { 16 if(sign == 0) { 17 sign = (c == '+' ? 1 : -1); 18 }else { 19 return 0; 20 } 21 }else if((c >= '0') && (c <= '9')) { 22 if(value > MAX / 10) { 23 return 0; 24 }else if(value == MAX / 10) { 25 if(c - '0' > MAX % 10 + 1) { 26 return 0; 27 }else if((c - '0' == MAX % 10 + 1) && (sign == -1) && (minMark == 0)) { 28 minMark = 1; 29 value = value * 10 + MAX % 10; 30 }else if(c - '0' <= MAX % 10) { 31 value = value * 10 + c - '0'; 32 }else { 33 return 0; 34 } 35 }else{ 36 value = value * 10 + c - '0'; 37 } 38 }else { 39 return 0; 40 } 41 index ++; 42 } 43 if(minMark == 1) { 44 return MIN; 45 }else if(sign == -1) { 46 value *= -1; 47 } 48 return value; 49 }