Leetcode: String to Integer (atoi)
I. Question
The objective of the question is to convert a string to an integer, that is, the atoi.
Ii. Analysis
The question is not difficult, but pay attention to the following points:
1. Blank before string
2. Positive and Negative Numbers of values represented by strings
3. The end condition ends when a non-digit or character '\ 0' is encountered.
4. Consider overflow, and compare it with the maximum value (0x7fffffff) and the minimum value that the int value can represent.
5. When abnormal input is considered, it is identified by the global variable valid. For "+/-" "0" "+ abc", it must be distinguished.
6. In addition, if "+-2" is processed during the test, 0 is returned. If it is a positive number, it is set to (0x7fffffff ), if it is a negative number, set it to (-0x7fffffff-1 ). I have an error in both of these places .... Therefore, it is not difficult for us to write programs after considering these situations. As follows:
Class Solution {public: int atoi (const char * str) {// bool flag = false for positive and negative numbers; // whether the negative number is less than 0x80000000 and int tmin = 0; long sum = 0; // judge whether the string is NULL if (str = NULL) return 0; // remove leading space while (* str = '') str ++; // indicates the number of digits to be judged. At that time, we thought we could have multiple symbols to get the last one. Later we found that only one symbol bit if (* str = '-') was allowed '-') {flag = true; str ++;} else if (* str = '+') {str ++ ;} // determine the validity of a number if (* str <'0' | * str> '9') return 0; // process the valid character value while (* str> = '0' & * str <= '9 ') {Sum = sum * 10 + * str-'0'; // checks whether the specified range is exceeded if (! Flag & sum> (int) 0x7FFFFFFF) {sum = (int) 0x7FFFFFFF; break;} else if (flag & sum> (int) 0x7fffff) {sum = (int) 0x7FFFFFFF; tmin = 1; break;} str ++;} // if (flag & tmin) sum =-sum-1; else if (flag &&! Tmin) sum =-sum; return sum ;}};