[Problem]
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.
[Analysis]
The main point of this question is to consider corner cases. Really can not pass OJ words reference spoiler basic is no problem.
[Solution]
Public classSolution { Public intatoi (String str) {str=Str.trim (); if(str.length () = = 0) { return0; } intSign = 1; inti = 0; if(Str.charat (0) = = ' + ') {i++; } if(Str.charat (0) = = '-') { sign=-1; I++; } Longresult = 0; for(; i < str.length (); i++) { intdigit = Str.charat (i)-' 0 '; if(Digit > 9 | | Digit < 0) { Break; } Else { if(Result > LONG.MAX_VALUE/10) { Break; } result*= 10; if(Result > Long.max_value-Digit) { Break; } result+=Digit; }} result= result *Sign ; if(Result >integer.max_value) {Result=Integer.max_value; } Else if(Result <integer.min_value) {Result=Integer.min_value; } return(int) result; }}
Leetcode #8 String to Integer (atoi) (E)