Algorithm improvement and optimization of string conversion to Integer

Source: Internet
Author: User

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;&AMP;&AMP;&NBSP;NUM&NBSP;&GT;&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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.