Title: Leetcode 008 String to Integer
Test instructions: Completes the function of the built-in function atoi to convert the string to an integer.
Lesson: Take it easy at first, then find that there are a lot of anomalies that need to be dealt with. Then according to the C + + reference on the atoi of the provisions of a write, only AC. There is also an overflow problem, the first thought that int will automatically handle the direct return of the boundary value, in fact, if the overflow of more than 2147483647 of the number will be negative, so to determine whether it will be large, but the problem is set to Longlong, It is also possible to overflow the longlong, so each time you change the ans you have to determine whether it is within the range of integers.
atoi function Rules: http://www.cplusplus.com/reference/cstdlib/atoi/
1, leading whitespace ignored
2, judge whether the ' + ', '-' as the leading to specify the positive or negative of the integer
3. A non-numeric character after an integer ignores the return of the preceding integer
4. If a valid integer cannot be formed, it will contain other jumbled characters and return 0
5, if the integer range is exceeded, the return int_max=2147483647 is greater than the return int_min=-2147483648.
The code is as follows:
classSolution { Public: intMyatoi (stringstr) { intLen = Str.size (), i =0, flag =1; Const intMAX =2147483647, MIN =-2147483648; Long LongAns =0; //there may be leading spaces while(Str[i] = =' ') i++; //may be preceded by a sign indicating positive or negative if(Str[i] = ='-') {flag= -1; I++; } Else if(Str[i] = ='+') i++; while(I <Len) { //guarantee that the added character is a valid number. if(Str[i] <='9'&& Str[i] >='0') {ans*=Ten; Ans+ = (str[i++]-'0'); if(Ans*flag > MAX)returnMAX; if(Ans*flag <min)returnMIN; } //There may be other characters at the end Else Break; } ans*=Flag; if(Ans > MAX)returnMAX; Else if(Ans <min)returnMIN; returnans; }};
"Leetcode" 008 String to Integer (atoi)