Preface a few days ago, the blogger saw Uncle mouse examine the compilation of atoi on Sina's meager page. Zhou sibo also had to interview Alibaba (ps: although the blogger is in the LNMP direction, but I am still confident that I can work together). Here I also implement these two functions to prevent the interview from failing to answer questions.
Atoi
# Include <stdio. h> # include <stdlib. h> # define INT_MAX 2147483647 # define INT_MIN-2147483648int myatoi (const char * s) {int val, flag; unsigned int cutlim, cutoff; // determine whether it is NULL if (s = NULL) return 0; // remove spaces and tabs while (* s = ''| * s = '\ t') s ++; // determine the if (* s = '-') {flag = 1; s ++;} else {flag = 0; if (* s = '+ ') s ++;} // pay attention to cross-border cutoff = flag? (Unsigned int) INT_MAX + 1: INT_MAX; cutlim = cutoff % 10; cutoff/= 10; for (val = 0; * s> = '0' & * s <= '9'; s ++) {if (val> cutoff | (val = cutoff & * s-'0'> cutlim) {return flag? INT_MIN: INT_MAX;} val = 10 * val + * s-'0';} if (flag) return val *-1; elsereturn val;} int main (void) {char str [100]; int num; while (scanf ("% s", str )! = EOF) {num = myatoi (str); printf ("% d \ n", num);} return 0 ;}
Itoa
# Include <stdio. h> # include <stdlib. h> # define N 15/*** returns or exchanges two numbers */void swap (char * a, char * B) {if (*! = * B) {* a = * a ^ * B; * B = * a ^ * B; * a = * a ^ * B ;}} /*** code for converting Integer type to string type on windows platform */void itoa (int value, char * str) {int I, j, k; // process negative values if (value <0) {str [0] = '-'; value * =-1;} else {str [0] = '+ ';} for (I = 1; value; I ++, value/= 10) {str [I] = value % 10 + '0 ';} // string reverse order for (j = 1, k = I-1; j <= k; j ++, k --) {swap (str + j, str + k);} // end ID of the completion string str [I] = '\ 0'; // forward a positive value to an if (str [0]! = '-') {For (j = 1; j <= I; j ++) {str [j-1] = str [j] ;}} int main (void) {int value; char str [N]; while (scanf ("% d", & value )! = EOF) {itoa (value, str); printf ("% s \ n", str);} return 0 ;}