String to Integer (atoi)
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.
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.
First step: Skip spaces
Step two: Determine the positive and negative
Step three: Remove the bits and check for overflow.
classSolution { Public: intAtoiConst Char*str) { //whitespace while(*str = =' ') Str++; // Sign intSign =1; if(*str = ='+') Str++; Else if(*str = ='-') { sign= -1; STR++; } // Number inty =0; while(*str >='0'&& *str <='9') { if(sign==1) { if(Y > int_max/Ten) returnInt_max; Else if(y = = int_max/Ten&& *str >='7') returnInt_max; Else{y= y*Ten+ (*STR-'0'); STR++; } } Else { if(Y > int_max/Ten) returnint_min; Else if(y = = int_max/Ten&& *str >='8') returnint_min; Else{y= y*Ten+ (*STR-'0'); STR++; } } } returny*Sign ; }};
"Leetcode" String to Integer (atoi)