Implement atoi to convert a string to an integer. Hint:carefully consider all possible input cases. If you want a challenge, please Dobelow and ask yourself what is the possible input cases. Notes:it is intended for Thisproblem 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 aConst Char*argument, click the Reload button to reset your code definition.spoilers alert ... click to show requirements foratoi. Requirements foratoi:the function First discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, the starting from Thischaracter, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and INTERPR ETS 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 Thisfunction. If The first sequence of non-whitespace characters in Str are not a valid integral number, orifNo such sequence exists because either str is empty or it contains only whitespace characters, no conversion is PERFO Rmed. 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 returned.
1. Pay attention to the details, pay attention to the limit of overflow how to return the value, and the method of weighting each digit into int.
2. Use of the Trim method in string.
1 Public classSolution {2 Public intmyatoi (String str) {3 intRes =0;4 if(str = =NULL){5 returnRes;6 }7str =Str.trim ();8 intLen =str.length ();9 BooleanIsnegative =false;Ten if(len = = 0){ One returnRes; A } - for(inti = 0; i<len; i++){ - if(I==0 && Str.charat (i) = = '-'){ theIsnegative =true; - Continue; - } - + Else if(I==0 && Str.charat (i) = = ' + '){ - Continue; + } A at Else if(Str.charat (i) >= ' 0 ' && str.charat (i) <= ' 9 '){ - intDigit = (int) (Str.charat (i)-' 0 '); - if(Res > (integer.max_value-digit)/10){ - if(isnegative) { - returnInteger.min_value; - } in Else{ - returnInteger.max_value; to } + } -res = res*10+Digit; the * } $ Else{Panax Notoginseng Break; - } the + A } the if(isnegative) { + return0-Res; - } $ Else{ $ returnRes; - } - the - }Wuyi}
Leetcode-string to Integer (atoi)