Programmer interview questions 100 (17)-converts a string to an integer

Source: Internet
Author: User

Http://zhedahht.blog.163.com/blog/static/25411174200731139971/

Question: enter a string that represents an integer, convert it to an integer, and output it. For example, if the input string is "345", an integer of 345 is output.

Analysis: although this question is not very difficult, the basic functions of C/C ++ language can be achieved, but the code written by different programmers for this question is very different, it can be said that this question can reflect the thinking and programming habits of programmers, so it has been used as an interview question by many companies, including Microsoft. It is recommended that you write the code before reading it, and then compare the differences between the code you write and the reference code below.

First, we will analyze how to complete the basic function, that is, how to convert the string representing an integer into an integer correctly. Or take "345" as an example. When we scan the string's first character '3', we do not know how many digits are behind it. We only know that this is the first character, so the number we get at this time is 3. When the second digit '4' is scanned, we now know that the first digit is 3, and a Number 4 is added to the end. The first digit 3 is 30, the resulting number is 3*10 + 4 = 34. Then we scanned the character '5' again. We already know that there are 34 in front of '5'. Because we need to add 5 in front, the 34 in front is equivalent to 340, the resulting number is 34*10 + 5 = 345.

From the analysis, we cannot come up with a conversion idea: every time a character is scanned, we multiply the previous number by 10 and add the number represented by the current character. This idea is not hard to achieve with loops.

An integer may not only contain numbers, but may also start with '+' or '-' to indicate positive and negative integers. Therefore, we need to perform special processing on the first character of this string. If the first character is '+', no operation is required. If the first character is '-', this integer is a negative number, in the end, we need to convert the obtained value to a negative number.

Next we try to handle illegal input. Since the pointer is input, the first thing we need to do before using the pointer is to judge whether the pointer is null. If you try to access a null pointer, the program will inevitably crash. In addition, the input string may contain characters that are not numbers. Every time we encounter these invalid characters, we do not need to continue the conversion. The last problem to consider is the overflow problem. Because the input number is input in the form of a string, it is possible that after a large number is converted, it will exceed the maximum integer that can be expressed and overflow.

Now the analysis is almost done, and you need to write the code. First, we should consider how to declare this function. Since the string is converted into an integer, we naturally think:

Int strtoint (const char * Str );

This statement seems no problem. But what value should I return when the input string is a null pointer or contains invalid characters? How about 0? So how can we distinguish between illegal input and the string itself being "0?

Next we will consider another idea. We can return a Boolean value to indicate whether the input is valid, and put the converted integer in the parameter list as a reference or pointer. Therefore, we can declare the following:

Bool strtoint (const char * STR, Int &
Num );

This approach solves the preceding problems. However, this function is not very convenient for users to use it, because it is not intuitive enough to assign the obtained integer value to other integer variables.

The first statement is intuitive. How can users be notified when illegal input is detected while the system is intuitive? One solution is to define a global variable, which is marked whenever an illegal input occurs. After calling this function, you can check the global variable to determine whether the conversion is successful.

The complete implementation code is written below. Reference code:

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 first char in the string maybe '+' or '-'            bool minus = false;            if(*digit == '+')                  digit ++;            else if(*digit == '-')            {                  digit ++;                  minus = true;            }            // the remaining chars in the string            while(*digit != '\0')            {                  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 == '\0')            {                  g_nStatus = kValid;                  if(minus)                        num = 0 - num;            }      }      return static_cast<int>(num);}

Discussion: In the reference code, I chose the first declaration method. However, during the interview, we can use any declaration method for implementation. However, when the interviewer asks us why we choose, we should evaluate the advantages and disadvantages of the two. The first declaration method is very intuitive for users, but it is not elegant enough to use global variables. The second method is to use the return value to indicate whether the input is legal. This method is used in many APIs, however, the function declared by this method is not intuitive enough.

Finally, it is worth mentioning that in the library functions provided by C language, function atoi can convert strings to integers. Its declaration is int atoi (const char * Str ). This function uses a global variable to indicate whether the input is valid.

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.