#include<limits.h>#define INT_MAX_DIV_BY_10 (INT_MAX / 10)#define INT_MAX_REM_BY_10 (INT_MAX % 10)#define INT_MIN_DIV_BY_10 (INT_MIN / 10)#define INT_MIN_REM_BY_10 (INT_MIN % 10)intmyAtoi(char*str){char*p=str,c;ints=1;intd;intv=0;while(c=*p++){if(c==' ')continue;if((c=='+'||c=='-')&&*p>='0'&&*p<='9'){if(c=='-')s=-1;break;}elseif(c>='0'&&c<='9'){p--;// point back to currect digitbreak;}else{return0;// invalid}}// handle empty string or it contains only whitespacesif(!c)return0;// at this time p must point to a digitwhile(c=*p++){if(c<'0'||c>'9')returnv;d=c-'0';if(s==1){// exceeds INT_MAX?if(v<INT_MAX_DIV_BY_10||(v==INT_MAX_DIV_BY_10&&d<INT_MAX_REM_BY_10))v=10*v+d;elsereturnINT_MAX;}else{// exceeds INT_MIN?if(v>INT_MIN_DIV_BY_10||(v==INT_MIN_DIV_BY_10&&-d>INT_MIN_REM_BY_10))v=10*v-d;elsereturnINT_MIN;}}returnv;}