Problem Description:
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 for the 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:
The Trim method is first called to remove white space characters on either side of the string. Then read from the beginning, if the beginning is ' + ', indicating that the value is a positive number, if the beginning is '-', indicating that the value is negative, if the first read ' + ' or '-', then read from the second, or still read from the first. The following begins to read backwards until the end of the string. If you read a number other than the character ' 0 '-' 9 ', then jump out of the loop and return the calculated value, otherwise the accumulated value is calculated continuously.
The code is as follows:
1 Public classSolution {2 Public intmyatoi (String str) {3 BooleanNegative =false;4 inti = 0;5 intresult = 0;6 intDigit;7 8 if(str = =NULL|| Str.length () = = 0)9 return0;Tenstr =Str.trim (); One if(str.length () = = 0) A return0; - if(Str.charat (0) = = '-' | | Str.charat (0) = = ' + ') { - if(Str.charat (0) = = '-') { theNegative =true; - } -i++; - } + while(I <str.length ()) { - if(Str.charat (i) > ' 9 ' | | Str.charat (i) < ' 0 ') + Break; Adigit = Str.charat (i)-' 0 '; at if(!negative && result > (integer.max_value-digit)/10) - returnInteger.max_value; - Else if(Negative && result >-((integer.min_value + digit)/10)) - returnInteger.min_value; - Else { -result = result * 10 +Digit; ini++; - } to } + returnNegative? -Result:result; - } the}
Java [Leetcode 8] String to Integer (atoi)