This is a very tragic inscription, all kinds of situations.
1, discard the front blank and the number behind the thing
2, the number will be entered continuously or with the symbol output, the middle of the other characters will be considered invalid, before the number of other characters will also be considered invalid.
3, 0777 is considered 777, pay attention to integer overflow.
1 classSolution {2 Public:3 intMyatoi (stringstr) {4 if(Str.empty ())return 0;5 string:: Iterator First=str.begin (), end=str.end ();6 intn=0, op_tag=0, num_tag=0, space_tag=0;7 Long Longmax=2147483647, num=0;8 Charop='+';9 while(first!=end)Ten { One while(*first==' ') {first++;space_tag=1;} A if(*first=='+'|| *first=='-' ) - { - if(op_tag==0) the { -op=*First ; -op_tag=1; -first++; + - } + Else return 0; A } at if(First! = end) &&isdigit (*First )) - { - while(First! = end) && isdigit (*First )) - { -n=*first-'0'; -num=num*Ten+N; infirst++; -num_tag=1; to if(Num > Max) Break; + } - } the Else Break; * if(num_tag==1|| space_tag==1|| op_tag==1) Break; $first++; Panax Notoginseng } - if(op=='-') the { + if(Num > (max+1) Num =-(max+1); A Elsenum=-num; the } + Else if(op=='+') - { $ if(Num>max) num=Max; $ } - returnnum; - the } -};
If you change the pointer to the next bidding clubs concise, the following is the online thinking
1 intAtoiConst Char*str) {2 intSign =1,Base=0, i =0;3 while(Str[i] = =' ') {i++; }4 if(Str[i] = ='-'|| Str[i] = ='+') {5Sign =1-2* (str[i++] = ='-'); 6 }7 while(Str[i] >='0'&& Str[i] <='9') {8 if(Base> Int_max/Ten|| (Base= = Int_max/Ten&& Str[i]-'0'>7)) {9 if(Sign = =1)returnInt_max;Ten Else returnint_min; One } A Base=Ten*Base+ (str[i++]-'0'); - } - return Base*Sign ; the}
String to Integer (atoi)