Test Instructions
Converts a string containing a number to an int type
Ideas
Implementation is not difficult, mainly considering a variety of situations.
1. string is not an empty string;
2. what to do with spaces or other characters in a string;
3. with the sign processing;
4. What to do if the number in the string exceeds the range of type int (int range:-2147483648~2147483647 0x80000000~0x7fffffff)
1 intMyatoi (Char*str) {2 intlen=strlen (str);3 intflag=1, i=0;4 Long Longans=0;5 if(len==0)6 return 0;7 Else if(len==1)8 {9 if(str[0]>='0'&& str[0]<='9')Ten returnstr[0]-'0'; One Else return 0; A } - Else - { the intI=0; - while(str[i]==' ') i++;//previous empty string skipped - if(str[i]=='-') {flag=-1; i++;} - Else if(str[i]=='+') {flag=1; i++;} + Else if(str[i]>='0'&& str[i]<='9') {flag=1;} - while(str[i]!=' /') + { A if(str[i]>='0'&& str[i]<='9') at { -ans=ans*Ten+str[i]-'0'; i++; - if(Flag*ans>int_max) {returnInt_max; Break;} - Else if(flag*ans<=int_min) {returnInt_min; Break;} - } - Else{returnAns*flag; Break;}//If a non-numeric string is encountered, the subsequent stop scan in - } to return(int) (ANS) *Flag; + } -}
leetcode.008 String to Integer (atoi)