Converts a string to a number.
Problem description:
Implement atoi to convert a string to an integer.
Solution:
Pay attention to the following points for a string:
1. filter all space characters starting with a string;
2. Pay attention to the "+" and "-" characters before the number characters to determine the plus and minus signs of the number;
3. Only numeric characters are processed. Once a non-numeric character is displayed, string processing is immediately stopped and processed results are returned;
4. When returning results, pay attention to the problem that numbers are out of bounds. The value cannot exceed the maximum value or be less than the minimum value.
Class Solution {public: int atoi (const char * str) {if (str = NULL) return 0; const char * pCur = str; long result = 0; int flag = 0;/* indicates whether the number is negative */while (* pCur = ''& * pCur! = '\ 0') pCur ++; if (* pCur =' \ 0')/* the string contains only Spaces */return 0; if (* pCur = '+')/* symbol before the processing string */pCur ++; else if (* pCur = '-') {flag = 1; pCur ++;} if (* pCur> '9' | * pCur <'0')/* illegal character after addition and subtraction, jump out of Processing */return 0; if (* pCur! = '\ 0') result = _ atoi_core (pCur, flag); return (int) result;} long _ atoi_core (const char * pCur, int flag) {long result; while (* pCur! = '\ 0') {if (* pCur> = '0' & * pCur <= '9') {result = result * 10 + * pCur-48; pCur ++;} if (result> 0x7FFFFFFF) {if (flag) return INT_MIN; else return INT_MAX ;} if (flag) result = 0-result; return result ;}};