Title Source: https://leetcode.com/problems/string-to-integer-atoi/
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.
Update (2015-02-10):
The signature of the C++
function had been updated. If you still see your function signature accepts a const char *
argument, please click on the reload button to reset your code Definition.
Problem Solving Ideas:
Write the code according to the requirements, can be summarized as follows:
1. String is empty or all spaces, return 0;
2. Prefix spaces for strings need to be ignored;
3. After ignoring the prefix space, the first character encountered, if it is ' + ' or '-', continue reading, if it is a number, start processing the number, if not the previous 2, return 0;
4. In the process of processing numbers, if the subsequent characters printable numbers, stop the conversion and return the current value;
5. In the above process, if the converted value is outside the range of type int, the maximum or minimum value of int is returned.
Java code:
1 Public classSolution {2 Public intmyatoi (String str) {3 intMax =Integer.max_value;4 intMin =-Integer.min_value;5 Longresult = 0;6str =Str.trim ();7 intLen =str.length ();8 if(Len < 1)9 return0;Ten intStart = 0; One BooleanNeg =false; A - if(Str.charat (start) = = '-' | | Str.charat (START) = = ' + ') { - if(Str.charat (start) = = '-') theNeg =true; -start++; - } - + for(inti = start; i < Len; i++) { - CharCH =Str.charat (i); + A if(Ch < ' 0 ' | | ch > ' 9 ') at Break; -result = Ten * result + (CH-' 0 ')); - if(!neg && Result >max) - returnMax; - if(Neg &&-result <min) - returnmin; in - } to if(neg) +result =-result; - the return(int) result; * } $ Panax Notoginseng};
Leetcode 8 String to Integer (string to int)