When I see such a problem, I think is a very simple problem, immediately think of a while loop to traverse the entire string, a character into a number, about this problem is not the first time encountered, so confidently write well and then go online to find the answer.
This is perhaps the ideal and the reality of the gap between the program and the answer to write their own pair, found that no place can be called write right. The answer mentions the Atoi function, which is a library function that converts a string to an integer.
Here is the specific implementation:
Long long strtointcode (const char *ptr, bool minus) { long long num = 0; while (*ptr != ') { if (*ptr >= ' 0 ' && *ptr <= ' 9 ') { int flag = minus ? -1 : 1; num = num * 10 + flag* (*ptr - ' 0 '); if ((!MINUS&NBSP;&&&NBSP;NUM&NBSP;>&NBSP;0X7FFFFFFF) | | (minus && num < (signed int) 0x80000000)//* Determine if overflow or overflow */ { num = 0; break; } ptr++; } else { num = 0; break; } } if (*ptr == ') { sign =&Nbsp;v_normal; } return num;} Int strtoint (const char *ptr) { sign = v_error; long long num = 0; if (ptr != null && *ptr != ' + ') { bool minus = false; if (*ptr == ' + ') { ptr++; } else if (*ptr == '-') { ptr++; minus =&nbSp;true; } if (*ptr != ') { num = strtointcode (Ptr, minus); } } return (int) num;}
The first step into the Strtoint function is to determine if the string is empty, and if the string is empty, it returns the illegal input directly.
Enum state{v_normal = 0,//normal v_error//illegal};int sign = v_error;/* SET global variable to determine if illegal input */
is not empty and the first character is not '% ', then the first character is + or-when the output is positive and negative. Then enter the Strtointcode function to convert the string to a number, where the overflow and bottom overflow are to be considered.
if ((!minus && num > 0x7FFFFFFF) | | (Minus && num < (signed int) 0x80000000)) /* Determine if overflow or overflow * * {num = 0; Break }
Questions about converting a string to an integer