Title Description
Enter a string consisting of numbers, convert it to an integer, and output. For example: Enter the string "123", the output integer 123.
Given the function prototype int strtoint (const char *str), the function of converting a string into an integer cannot be atoi using a library function.
Analysis and Solution
The basic idea is to scan the string from left to right, multiply the previously obtained number by 10, and then add the number represented by the current character.
However, we need to consider the following issues:
- When the input is a null pointer
- The sign in front of the number
- Illegal characters
- Plastic overflow
The top three issues are easy to solve, and the main consideration is the problem of plastic overflow. In general, when an overflow occurs, the maximum or minimum int value is returned. Let's set up a few variables first:
- Sign is used to denote the positive and negative numbers
- n is used to store converted Results
- c is used to represent the current number
To determine whether the given number is beyond the maximum value that INT can represent, we compare the size of n and MAX_INT/10, i.e.:
- If n > Max_int/10, then the last conversion, N * 10 must be greater than man_int, so this time directly return Max_int
- if n = = MAX_INT/10, then compare the size of the last number C and max_int% 10, if C > Max_int% 10, then return Max_int
The complete code is as follows:
int strtoint (const char* STR) { static const int max_int = (int) ((unsigned) ~0 >> 1); static const int min_int =-(int) ((unsigned) ~0 >> 1)-1; unsigned int n = 0; ? // determine if the input is empty if (str = = 0) { return 0; } ? // Working with Spaces while (Isspace (*STR)) ++STR; ? // processing positive and negative int sign = 1; if (*str = = ' + ' | | *str = = '-') { if (*str = = '-') sign =-1; ++STR; } ? // The loop is not executed until the number is determined while (IsDigit (*STR)) { // Handling Overflow int c = *str-' 0 '; if (Sign > 0 && (n > MAX_INT/10 | | (n = = Max_int/10 && C > Max_int% 10))) { n = max_int; Break } else if (sign < 0 && (n > (unsigned) min_int/10 | | (n = = (unsigned) MIN_INT/10 && C > (unsigned) min_int% 10))) { n = min_int; Break } ? // multiply the previously obtained numbers Ten , plus the number represented by the current character. n = n * ten + C; ++STR; } Return sign > 0? N:-N; } |
Extrapolate
- Implementing a string-to-double conversion
Convert strings to integers