String to Integer (atoi) leetcode
The question is to convert a string to a number.
The focus of this question is to deal with various input situations.
There is a large English section below the question:
Requirements for atoi:
The function first discards as your whitespace characters as necessary until the first non-whitespace character is found. then, starting from this character, takes an optional initial plus or minus sign followed by as your numerical digits as possible, and interprets them as a numerical value.
The string can contain in additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is saved med.
If no valid conversion cocould be specified med, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
The above prompts some possible input or input that requires attention:
1. The leading space symbol, for example, "_ 123", indicates the space processing method (ignore)
2. We don't need to care too much about the positive and negative signs behind the spaces, but when the positive and negative signs appear at the same time, it will be wrong. The negative signs need to be recorded, because there will be overflow in the future.
3. The value 0 after the plus or minus signs is treated as "+ 0000123" (ignored)
4. If other characters are displayed, the system returns 12 if the number previously converted is "+ 12abc45", for example, "+ abc123", the system returns result = 0. The initial value of result is 0.
5. In case of overflow, You need to reserve the negative number to check whether the problem exists.
The Code is as follows:
Class Solution {public: int atoi (const char * str) {if (str = NULL) return 0; while (* str = '') // ignore the space + + str before the string; bool positive = false; if (* str = '+') // indicates whether the front has a positive number {positive = true; + + str;} bool negative = false; // indicates whether it is a negative number or whether there is a negative number before if (* str = '-') {negative = true; + + str;} while (* str = '0') // remove the 0 + + str after the plus or minus sign; if (negative & positive) // return 0 is returned when both positive and negative signs exist; long result = 0; while (* str! = '\ 0') {if (* str> = '0' & * str <= '9') {result = result * 10 + * str-'0 '; if (negative = false & result> INT_MAX) // determines whether the number is greater than the maximum number. return INT_MAX; if (negative = true &-result