We know that C language has a library function atoi (representing alphanumeric to integer) is a function that converts a string into an integer number. So how do we implement this function?
Many students will soon write the following code:
int Strtoint (char str[]) {assert (str); int Num=0;while (*STR) {num=num*10+*str-' 0 '; ++str;} return num;}
Does this code have any loopholes? Although the assert is used to check the null pointer, imagine if the string we passed in is a signed number? The plus sign of a positive integer can be omitted, but negative? should not be modified again. In addition, the string we passed in cannot be modified. You should use the const modifier. Considering the problem of positive and negative numbers, we add a flag flag to the program to record positive and negative numbers. The improvement procedure is as follows:
int strtoint (const char str[]) {assert (str); int num=0;int flag=1;if (*str== ' + ') {str++;} else if (*str== '-') {flag=-1;str++;} while (*STR) {num=num*10+*str-' 0 '; str++;} return flag*num;}
Next, do we have to consider checking for illegal input at the beginning? Check the illegal input, is it still need to consider the overflow problem? These are a good programmer to consider the scope. Let's take a look at the answer to this question in the book "The Sword Point offer".
The reference code is as follows:
Long long strtointcore (Const char* str, bool minus); enum Status { Kvalid = 0, kinvalid};int g_nstatus = kvalid;int strtoint (const char* &NBSP;STR) { g_nstatus = kinvalid; long long Num = 0; if (str != null && *str != ') ) { bool minus = False; if (*str == ' + ') str ++; else if (*str == '-') { str ++; minus = true; } if (*str != ') { num = strtointcore (Str, minus); } } return (int) num;} Long long strtointcore (Const char* digit, bool minus) { Long long num = 0; while (*digit != ') { if (*digit >= ' 0 ' & & *digit <= ' 9 ') { int flag = minus ? -1 : 1; &nbsP; num = num * 10 + flag * (*digit - ' 0 '); if ((!MINUS&NBSP;&&&NBSP;NUM&NBSP;>&NBSP;0X7FFFFFFF) | | (minus && num < (signed int) 0x80000000)) { num = 0; break; } digit++; } else { num = 0; break; } } if (*digit == ') { g_nstatus = kvalid; } return num;}
A simple question can be written in such a long code after careful consideration, this example is a warning to us, to consider the possible situation, to reduce the bug. Hope to bring some help to beginners.
This article from "Lime Childe" blog, reproduced please contact the author!
Algorithm improvement and optimization of string conversion to Integer