The main step
1.delete space in front of STR
2.check if Str startsWith other characters
3.check if STR is positive
4.check the end of STR
5.check if overflow
Public classSolution { Public intmyatoi (String str) { while(Str.length () > 0 && str.charat (0) = = ") {str= str.substring (1); } if(str.length () = = 0 | | (Str.charat (0)! = ' + ' && str.charat (0)! = '-' &&!isnum (Str.charat (0)))) { return0; } intPositive = 1; if(Str.charat (0) = = ' + ') {str= str.substring (1); } Else if(Str.charat (0) = = '-') {Positive=-1; STR= str.substring (1); } BooleanFLG =true; inti = 0; for(; i < str.length (); i++) { if(!Isnum (Str.charat (i))) {FLG=false; Break; } } if(!FLG) {STR= str.substring (0, i); } if(Str.length () > 11) { returnPositive = = 1?Integer.MAX_VALUE:Integer.MIN_VALUE; } if(str.length () = = 0) { return0; } Long tmp=long.valueof (str); if(tmp >integer.max_value) { returnPositive = = 1?Integer.MAX_VALUE:Integer.MIN_VALUE; } returnInteger.valueof (str) *positive; } Public BooleanIsnum (Charc) {returnC <= ' 9 ' && C >= ' 0 '; }}
[Leetcode] String to Integer (atoi)