String to integer "123"-> 123
Description:
Enter a string composed of digits, convert it to an integer, and output it. For example, input string "123" and output integer 123.
Given function prototypeint StrToInt(const char *str)
To convert a string to an integer. You cannot use the database function atoi.
Question Analysis:
To convert a string to an integer
① When scanning the first character '1', the number 1 is obtained directly because it is the first character.
② When scanning the second character '2,1*10+2 = 12
③ When the scan character '3' continues,12*10+3=123
That's whyn = n * 10 + c;
Easy to error:
1) it cannot be a null pointer. Otherwise, the program will crash when the NULL pointer is accessed.if(str == NULL)return 0;
2) Positive and Negative symbols must be considered.Add sign
3) consider invalid characters, such as spaces.While (isspace (* Str) ++ STR also needs to be detected when it is a number before conversion starts.
4) integer overflow. If a long and long string is input, it may be converted into integer overflow.Method 1: The N type can be defined as long. Method 2: Use the max_int and min_int types to compare the sizes of N and max_int/10.
<<
Reference code:
Int strtoint (const char * Str) {// reverse the value of 0 and move one static const int max_int = (INT) (unsigned )~ 0> 1); static const int min_int =-(INT) (unsigned )~ 0> 1)-1; unsigned int n = 0; // determines whether it is null if (STR = NULL) return 0; // process space while (isspace (* Str) + + STR; // process positive and negative int Sign = 1; if (* STR = '+' | * STR = '-') {If (* STR = '-') Sign =-1; ++ STR ;} // after confirming the number, start converting while (isdigit (* Str) {// handle 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;} n = N * 10 + C; ++ STR;} return sign> 0? N:-N ;}