String to Integer (atoi): https://leetcode.com/problems/string-to-integer-atoi/
Problem description
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.
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.
Analytical
The difficulty lies in the handling of various special cases:
Various input Exceptions :
"+0", "0", "0", all should return 0
"+123", "+123", "123", "123ab123" should all return 123
"-123", return-123
"", "+", "-", "abc", "+-1", "~", etc. should return 0
and overflow :
"2147483648" return Int_max (2147483647)
"-21474836480" return Int_min (-2147483648)
It is important to note how to differentiate between the correct 0 and the error characters returned by 0:
Defines a global variable that is used to mark the wrong 0
intG_error =0;intMyatoi (char* Strl) {if(Strl = = NULL) {G_error =-1;return 0; }//Skip spaces while(*strl!=' + '&&*strl=="') {strl++; }int Sign=0;//sign bit, negative number is 1, positive number is 0 if((strl[0] ==' + '|| strl[0] =='-') && strl[1] ==' + ') {G_error =-2;return 0; }Else if(strl[0] ==' + ') { Sign=0; strl++; }Else if(strl[0] =='-') { Sign=1; strl++; } Long result =0; for(;*strl!=' + '; strl++) {intnum =*strl-' 0 ';if(Num <0|| num >9) { Break; }Else{result = result*10+ num;//Handling overflow if( Sign&& (Result > Int_max)) {G_error =-3;returnInt_min; }if(! Sign&& (Result > Int_max)) {G_error =-3;returnInt_max; } } }return Sign? -result:result;}
Leetcode | String to Integer (atoi)