Topic:
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.
Translation:
Implement a Atoi function to convert a string to an integer variable.
Analysis:
The AC rate of this problem is only 13.4%, mainly because of the handling of special cases. There are several situations that need to be considered:
1. The preceding space
2. After removing the preceding space, you can start with "+ 、-、 0", you need to do the corresponding processing
3. In addition to the starting point can be mentioned in the first 2 cases of non-numeric characters, the other place once the character is ignored, and then the character
4. Consider the boundary, i.e. whether it exceeds integer.max_value,integer.min_value. The following scenario uses long as a temporary storage, making it easier to make boundary judgments. But also to consider whether it will exceed the maximum value of long, so I use length to make a preliminary judgment.
Java version of Code (time complexity O (n)):
Public classSolution { Public int Myatoi(String str) {Char[] Chararr=str.tochararray (); Long result=0Lintstartindex=0; Boolean flag=true;//Positive intLength=0; for(intI=0; i<chararr.length;i++) {if(startindex==i) {if(chararr[i]=="') {startindex++;Continue; }if(chararr[i]==' + '|| chararr[i]==' 0 '){Continue; }if(chararr[i]=='-') {flag=false;Continue; } }if(chararr[i]>=' 0 '&&chararr[i]<=' 9 ') {result=result*Ten+chararr[i]-' 0 '; length++;if(length>Ten){ Break; } }Else{ Break; } }if(flag) {if(Result>integer.max_value) {returnInteger.max_value; } }Else{Result=-result;if(Result<integer.min_value) {returnInteger.min_value; } }returnResult.intvalue (); }}
Leet Code OJ 8. String to Integer (atoi) [Difficulty:easy]