String to Integer (atoi)

Source: Internet
Author: User

Implement atoi to convert a string to an integer.

Hint:carefully consider all possible input cases. If you want a challenge, please don't see below and ask yourself what is the possible input cases.

Notes:it is intended-problem to be specified vaguely (ie, no given input specs). You is responsible to gather all the input requirements up front.

Requirements for Atoi:

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, the starting from this character, takes a optional initial plus or minus sign followed by as many numerical digits as P Ossible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which is ignored and has no Effe CT on the behavior of this function.

If the first sequence of non-whitespace characters in STR isn't a valid integral number, or if no such sequence exists be Cause either str is empty or it contains only whitespace characters, no conversion is performed.

If No valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, Int_max (2147483647) or int_min ( -2147483648) is Returne D.

Problem Solving Ideas:

Various boundary problems need to be considered.

Cross-border issues? (whether to overflow int)

Sign question? (The first bit is ' + ' or '-' or ' ' 0-' 9 ')

Space problem? (with Trim)

There is a way to judge whether the overflow is pervasive and ingenious, using such a judgment:

1. INTEGER.MAX_VALUE/10 < result; The current conversion result is larger than the maximum/10 in the integer (because this judgment is placed at the start of the while loop, and then the result is *10+ the current traversal of the element, so if you also multiply by 10, the result is more than integer.max_value/ 10 also big, imagine, by 10 greater)

2. INTEGER.MAX_VALUE/10 = = Result && integer.max_value%10 < (Str.charat (i)-' 0 ')//The other is, the current result is exactly the same as the Integer . MAX_VALUE/10 is equal, the value of the currently traversed element is determined by the size of the last digit of the maximum value.

The subject as long as a slight careless error, note: "12ABC" convert to int is ' 12 ', that is, the idea from the left is not a space from the beginning to the right, the number encountered is valid until the stop encountered is not a number.

So the code uses result = result * + (Str.charat (i)-' 0 ')

Java Code

  Public intmyatoi (String str) {if(str = =NULL|| Str.length () < 1) {            return0; } STR= Str.trim ();//trim white spaces at beginning and end        CharFlag = ' + '; //check negative or positive        inti = 0; if(Str.charat (0) = = '-') {flag= '-'; I++; }Else if(Str.charat (0) = = ' + ') {i++; }                intresult = 0; //Calculate Value         while(Str.length () > I && str.charat (i) >= ' 0 ' && str.charat (i) <= ' 9 ') {            if(INTEGER.MAX_VALUE/10 < Result | | (INTEGER.MAX_VALUE/10 = = result && integer.max_value%10 < (Str.charat (i)-' 0 '))){                   returnFlag = = '-'?Integer.MIN_VALUE:Integer.MAX_VALUE; } result= result * + (Str.charat (i)-' 0 '); I++; }                returnflag== '-'? -Result:result; }

Reference:

1. http://www.cnblogs.com/springfor/p/3896499.html

String to Integer (atoi)

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.