The key point of the Atoi function is to think about the test case:
- The input is an empty string and the output is 0;
- The input string size exceeds Int_max output int_max;
- The input string size is less than int_min output int_min;
- The input string contains irregular characters and interrupts atoi, such as "01a4" Output 1;
- The input string begins and ends with spaces, ignoring spaces, such as input "+01" Output 1;
- The input string begins with "+" and "-", except for spaces, as entered correctly.
classSolution { Public: intAtoiConst Char*str) { if(strlen (str) = =0)return 0; Doubleresult=0; intj=0; while(str[j]==' ')//Ignore string first space{J++; } intlast = strlen (str)-1; intLast_space =0; while(str[last]==' ')//Ignore string trailing spaces{ Last--; Last_space++; } if(str[j]=='+') { for(inti=j+1; I<strlen (str)-last_space;i++) { if(str[i]>='0'&&str[i]<='9') {result= result*Ten+ (str[i]-'0'); } //terminating conversion If illegal characters are encountered Else { Break; } } if(result>Int_max) { returnInt_max; } Else { returnresult; } } if(str[j]=='-') { for(inti=j+1; I<strlen (str)-last_space;i++) { if(str[i]>='0'&&str[i]<='9') {result= result*Ten+ (str[i]-'0'); } Else { Break; } } if(Result* (-1) <int_min) { returnint_min; } returnresult* (-1); } for(intI=j;i<strlen (str)-last_space;i++) { if(str[i]>='0'&&str[i]<='9') {result= result*Ten+ (str[i]-'0'); } Else { Break; } } if(result>Int_max) { returnInt_max; } if(Result* (-1) <int_min) { returnint_min; } returnresult; }};
Implementing the Atoi function