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 for the problem to be specified vaguely (ie, no given input specs). You is responsible to gather all the input requirements up front.
Spoilers alert ... click to show requirements for atoi.
Requirements for Atoi:
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, the starting from this character, takes a optional initial plus or minus sign followed by as many numerical digits as P Ossible, and interprets 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 of this function.
If the first sequence of non-whitespace characters in STR isn't a valid integral number, or if no such sequence exists be Cause either str is empty or it contains only whitespace characters, no conversion is performed.
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 Returne D.
In short, the topic requires the realization of atoi function.
In g++, such as +-+-10,-+-+10, and +-+10 constants are legal, with values of 10, 10, and 10 respectively.
In this topic, this type of writing would require a return of 0. That is, only one + or-.
Class Solution {public: int atoi (const char *str) { while (*str = = ') ++str; const BOOL Isneg = *STR = = '-'? True:false; if (*str = = ' + ' | | *str = = '-') ++str; Don't support +-+-etc. int result = 0; while (*str >= ' 0 ' && *str <= ' 9 ') { const int digit = *STR-' 0 '; if (!isneg && (int_max-digit)/10 < result)//it is <, not <= return int_max; else if (Isneg && (int_min+digit)/10 > Result)//It is, and not >= return int_min; else result = result * + (Isneg?-digit:digit); ++str; } return result;} ;
If the
else if (Isneg && (int_min+digit)/10 > Result)//It is, and not >= return int_min;
> Written in >=, is nothing more than being Leetcode AC.
However
if (!isneg && (int_max-digit)/10 < result)//it is <, not <= return int_max;
Will < writing <=, is can be AC. But in fact it is wrong, it seems leetcode test case is not sufficient.
Input string, "2147483646", you can distinguish between the use of < and <= difference.
String to Integer (atoi)--Leetcode