Converts a string to an integer

Source: Internet
Author: User
Tags function prototype
30th Chapter, string conversion to Integer

First look at the topic:

Enter a string representing an integer that converts the string to an integer and outputs, such as the input string "345", and the output is an integer 345.
Given the function prototype int strtoint (const char *STR), complete the function Strtoint, the function of converting the string into an integer, not using the library function atoi (even if permitted to use, its handling of overflow situation can not meet the requirements of the problem, Please refer to the end of section 7th below for details.

Let's take a step-by-step analysis (a total of 9 bars, focusing on the 8th and subsequent sections below) until the first accurate code is written:

1, the subject of the test is actually a string conversion to an integer problem, or that you want to implement the Atoi function. So how do you convert a string that represents an integer to an integer correctly? Take "345" as an example:

When we scanned the string's first character ' 3 ', we got the number 3 because we knew it was the first bit. When the second digit ' 4 ' is scanned, and we know that there is a 3 ahead, we then add a number 4, and the front 3 equals 30, so we get the number: 3*10+4=34. Continue to scan to the character ' 5 ', ' 5 ' front already has 34, because the preceding 34 equals 340, plus the later scan to 5, the final number is: 34*10+5=345.

So the idea is that every time we scan a character, we multiply the number we got before by 10, and then add the number that the current character represents.

2,There are some details to note, as Zhedahht says: "Since integers may not only contain numbers, it is also possible to start with ' + ' or '-' to denote the positive or negative of an integer. So we need to do a special deal with the first character of this string. If the first character is a ' + ', there is no need to do anything; if the first character is a '-', it means that the integer is a negative number, and at the end we want to turn the resulting value into a negative number. Then we try to deal with the illegal input. As the pointer is entered, the first thing to do before using the pointer is to determine if the pointer is empty. If you try to access the null pointer, it will inevitably cause the program to crash. In addition, the input string may contain characters that are not digits. Whenever we encounter these illegal characters, we do not need to continue the conversion. The last question to consider is the overflow problem. Since the number entered is entered as a string, it is possible to enter a large numeric conversion that will overflow beyond the maximum number of integers that can be represented. "For example, when you give a string as shown in the picture on the left, do you think about it?" Of course, their corresponding correct output is shown in the picture on the right (assuming you are under a 32-bit system and the compilation environment is VS2008 above):3,Soon, you may be able to write the following code:[CPP] View Plain copy print? copyright@zhedahht 2007      enum status {kvalid = 0,  kinvalid};   int g_nstatus = kvalid;     // convert a  string into an integer    Int strtoint (CONST&NBSP;CHAR*&NBSP;STR)     {       g_nStatus = kInvalid;        long long num = 0;          if (Str != NULL )        {           const  char* digit = str;              //  the first char in the string maybe  ' + '  or  '-'            bool minus = false;   &NBSp;       if (*digit ==  ' + ')                 digit ++;            else if (*digit ==  '-')            {                digit ++;               minus = true;           }               // the remaining chars in the string             while (*digit !=  ')             {               if (*digit  >=  ' 0 '  && *digit <=  ' 9 ')                 {                    num = num * 10 +  (*digit -  ' 0 ');                        // overflow                       if (Num > std::numeric_limits<int>::max ())                     {                         num = 0;                        break;                    }                       digit ++;                }                // if the char is not a digit, invalid  Input                else               {                    num = 0;                    break;               }            }              if (*digit ==  ' ")            {                g_nStatus = kValid;                if (minus)                     num = 0 - num;            }       }        return static_cast<int> (num);  }  

//COPYRIGHT@ZHEDAHHT 2007 enum Status {kvalid = 0, kinvalid}; int g_nstatus = Kvalid;
	Convert a string into an integer int strtoint (const char* str) {g_nstatus = Kinvalid;

	Long Long num = 0;

		if (str!= NULL) {const char* digit = str;
		The maybe ' + ' or '-' bool minus = false;
		if (*digit = = ' + ') digit + +;
			else if (*digit = = '-') {digit + +;
		minus = true;
			}//The remaining chars in the string while (*digit!= ' ") {if (*digit >= ' 0 ' && *digit <= ' 9 ')

				{num = num * + (*digit-' 0 ');
					overflow if (num > Std::numeric_limits<int>::max ()) {num = 0;
				Break
			} digit + +;
				}//If the char is not a digit, invalid input else {num = 0;
			Break
			} if (*digit = = ' is ') {g_nstatus = Kvalid;
		if (minus) num = 0-num;
} return static_cast<int> (num); }
    Run under the above program, you will find that when the input string is the Red fork in the following part of the corresponding, the program result error:       

    Two questions: when the input string is not a number but a character, such as "1a", the above program returns 0 directly (and the correct result should be 1): [CPP] view plain copy Print?  if the char is not a digit, invalid input                       else                       {                          num = 0;                          break;                       }  

If the is not a digit, invalid input
				  else
				  {
					  num = 0;
					  break;
				  
There is a problem handling the overflow. Because it encountered an overflow condition, it returned directly to 0: [CPP]View Plain copy print?                       overflow if (num > Std::numeric_limits<int>::max ()) {                       num = 0;                   Break }
Overflow  
				if (num > Std::numeric_limits<int>::max ())
				{
					num = 0;
					break;
				

4,To fine-tune the code, as follows (note: The library function atoi specified above the int value, according to the maximum maxint:2147483647, over the-int by the minimum minint:-2147483648):[CPP] View Plain copy print? Copyright@sp_daiyq 2013/5/29    int strtoint (const char* str)    {        int res = 0; // result         int i = 0; // index of str        int  signal =  ' + '; // signal  ' + '  or  '-'         int cur; // current digit           if  (! STR)            return 0;           // skip backspace        while  (isspace (str[i))            i++;           // skip signal        if  (str[i] ==&nbSP; ' + '  | |  str[i] ==  '-')        {            signal = str[i];           i++;        }          // get result        while  (str[i] >=  ' 0 '  && str[i]  <=  ' 9 ')        {            cur = str[i] -  ' 0 ';               // judge overlap or not             if  (  (signal ==  ' + ')  &&  (cur > int_max -  RES*10)  )            {               res = int_max;                break;            }           else if  (  signal ==   ')  &&  (cur -1 > int_max - res*10)  )            {                res = INT_MIN;                break;           }               res = res * 10 + cur;            i++;       }          return  (signal ==  '-')  ? -res : res;  }   

//copyright@sp_daiyq 2013/5/29 int strtoint (const char* str) {int res = 0;//result int i = 0;//IND Ex of str int signal = ' + '; Signal ' + ' or '-' int cur;

	Current digit if (!STR) return 0;

	Skip backspace while (Isspace (str[i)) i++;
		Skip signal if (str[i] = = ' + ' | | | str[i] = = '-') {signal = Str[i];
	i++;

		}//Get result while (Str[i] >= ' 0 ' && str[i] <= ' 9 ') {cur = str[i]-' 0 ';
			Judge overlap or not if ((signal = = ' + ') && (cur > int_max-res*10)) {res = Int_max;
		Break
			else if ((signal = = ") && (Cur-1 > Int_max-res*10)) {res = int_min;
		Break
		res = res * + cur;
	i++; return (signal = = '-')?
-res:res; }
At this point, the 1th small question (when the input string is not a number, but a character) is resolved at the end of section 3rd of the above: However, the 2nd minor problem described at the end of section 3rd: The overflow problem was not resolved. That is, when given the following test data, the question is: what is the problem with the correct result of the string code that needs to be converted to run the results? For example, using the above code to convert this string: "10522545459", it should be the correct result should be 2147483647, but the actual result of the program is: 1932610867. Therefore, it is obvious that the program does not solve the 2nd small problem above: overflow problem. What is the reason? Let's analyze the code to see how the overflow is handled specifically: [CPP] View Plain copy print?  judge overlap or not            if   (  (signal ==  ' + ')  &&  (cur > int_max - res*10)  )            {                res = INT_MAX;                break;           }            else if  (  (signal ==  '-')  &&  (cur -1 > int_max - res*10)  )             {                res = INT_MIN;   &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBsp;   break;           }  
Judge overlap or not
		if ((signal = = ' + ') && (cur > int_max-res*10))
		{
			res = Int_max;
			break;
		else if ((signal = = ") && (Cur-1 > Int_max-res*10))
		{
			res = int_min;
			break;
		
Then the example above, for example, given the string "10522545459", minus 11 bits of space, and Max_int, that is, 2147483647 is 10 digits, when scanned to the last character ' 9 ', the program compares 9 and 2147483647-1052254545      The size of the *10. The problem immediately exposed, because at this time let res*10, that is, let 1052254545*10 > Max_int, overflow Undoubtedly, the program has been wrong, and then execute the following line of code is meaningless: [CPP]View Plain copy print? Cur > int_max-res*10
Cur > int_max-res*10
That is, for the string "10522545459", when scanning to the last character ' 9 ', the idea of converting to an integer according to the string in section 1th above is: "Every time we scan a character, we multiply the number we got before by 10, and then we add the number that the current character represents," In order to get the final integer, we have to calculate this:

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.