Convert strings to integers

Source: Internet
Author: User

Problem Description: Enter a string consisting of a number, convert it to an integer and output, requiring that the system-provided conversion function or method cannot be used.

For example: Enter the string "123", the output integer 123.

Many programming languages provide functions or methods for strings and various types of conversions, but we also want to write the appropriate conversion methods or functions ourselves, and other types of conversions are similar.

Here I take the string conversion to integral type as an example, to introduce.

Analysis: The basic idea is to scan the string from left to right, multiplying the previously obtained number by 10, plus the number represented by the current character. However, there are several issues to be aware of during the conversion process.

1, empty string input: The input is an empty string, the conversion of an empty string, the program may crash, so you need to determine whether the string is empty. We agreed to return 0 when the string is empty.

2, sign: The string may not only contain numbers, but also may be a ' + ' or '-' in the beginning of a positive and negative integer string, so the first character needs to be special processing.

3. Illegal characters: The input string may contain characters that are not numbers or "+" or "-". Therefore, we have agreed that whenever these illegal characters are encountered, the conversion is stopped, returning 0.

4. Integer overflow: The number entered is entered as a string, so entering a very long string may result in an overflow. Therefore, the boundary problem should be considered. We agree:

Returns the maximum value of an integer when the value of the conversion is greater than the maximum value of the integer type;

Returns the minimum value of an integer when the value of the conversion is less than the minimum value of the integer type;

Of the four problems above, the most difficult to deal with is the overflow problem, so there are two ways to solve the overflow.

Method One: Define a larger range of variables as the result of the conversion, and compare the result of the conversion with the maximum and minimum values of the integral type to determine if overflow. This method is relatively simple, I no longer write program implementation.

Method Two: The reader can be combined with the following code to understand, before converting a bit character,

For positive integers, the size of the previously converted results (Strint in this code) and MAX/10 are compared first:

If Strint > Max/10, then the Strint *10 must be greater than max when the last step is converted, and this returns max.

if Strint = = MAX/10, then compare the size of the digit C and max% 10, if C > Max% 10, return Max directly.

For negative integers, the results of the previous conversion (Strint in this code) and the size of MIN/10 are compared, namely:

If -1*strint < MIN/10, then the last step conversion, -1*strint *10 must be less than min, this time directly return min.

if -1*strint = = MIN/10, then compare the size of the bit number -1*c and min% 10, if -1*c < min% 10, directly return to Min.

Because the second method is more troublesome, here I give the second method of Java program code, code is more common, the reader can easily convert to other language implementation.

It is important to note that the integer in Java accounts for 4 bytes, that different programming languages may not be the same, and that the reader needs to make appropriate adjustments in conjunction with its own programming language.

To summarize: The complete Java code is as follows:

1 ImportJava.util.*;2  classTest {3        Public Static intstringtoint (String str) {4          intn=str.length ();5          intStrint=0;6          intSign=1;//symbol Sign7          if(n==0)return0;//returns 0 if the string is empty8          9          if(Str.charat (0) = = ' + ')//pre-processing the first character, because the first character may have a sign bitTenSign=1; One          Else if(Str.charat (0) = = '-') ASign=-1; -          Else if(Str.charat (0) >= ' 0 ' && str.charat (0) <= ' 9 ') -Strint=str.charat (0)-' 0 '; the               Else  returnStrint; -           -          intMax= (int) (Math.pow (2,31)-1);//integer is the maximum value of positive number, because in Java, the 4 bytes of shaping, different languages may not be the same, the reader needs to adjust their own -          intMin= (int) Math.pow ( -2,31);//the minimum value of the integer as a negative number +           for(inti=1;i<n;i++)//process subsequent characters sequentially -          {    +              if(Str.charat (i) < ' 0 ' | | str.charat (i) > ' 9 ')return0;//If non-numeric characters appear in subsequent characters, 0 is returned directly A              intC=str.charat (i)-' 0 '; at              if(Sign==1 && (strint > MAX/10 | | (Strint = = MAX/10 && C > Max% 10)))//Maximum out-of- bounds processing -                  returnMax; -              if(Sign==-1 && ( -1*strint &LT;MIN/10 | | ( -1*strint== min/10 && -1*c < min% 10)))//Minimum out-of- bounds processing -                  returnmin; -              -Strint=strint*10+c;//normal handling of characters for each bit of a string in          } -          returnSign*strint;//Normal return results to       } +     } -   the  Public classMain { *      Public Static voidMain (string[] args) { $String str=NewString ("21474836");//The reader can perform a variety of tests as needed, no longer an examplePanax NotoginsengSystem.out.println ("str=" +str); -SYSTEM.OUT.PRINTLN ("After converting to Integer:" +test.stringtoint (str)); the        +     } A  the}
View Code

The output is:

str=-21474836
After conversion to integer:-21474836

The reader can then verify the example itself.

This topic gives the method of converting a string to integers and several issues to be noted, and there are other similar conversion problems in real programming, such as converting a string to a floating point (and also considering a decimal point), and so on.

But this topic gives us a way to change, and there are problems to be aware of, in short, for each type, carefully consider each type of special case. For other types of conversions, this article no longer describes, the reader can follow this idea of programming can be considered.

Convert strings to integers

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.