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.
The principle of atoi:
1. If there is a space in front of the string, remove all spaces
2. Allow sign, need to read the sign, two consecutive sign is the wrong string
3. After reading the sign, start reading the number until you read the position that is not a number or stop at the end of the string, resolving the number inside
Note overflow, return Int_max or int_min when overflow
1 classSolution {2 Public:3 intAtoiConst Char*str) {4 if(Str==null)return 0;5 intresult=0;6 intflag=1;7 while(*str==' ')8 {9str++;Ten } One if(*str=='+') A { -flag=1; -str++; the } - Else if(*str=='-') - { -flag=-1; +str++; - } + while(*str>='0'&&*str<='9') A { at - intdigit=*str-'0'; - if(result<=int_max/Ten) - { -result*=Ten; - } in Else - { to if(flag==1)returnInt_max; + Else returnint_min; - } the * if(result<=int_max-Digit) $ {Panax Notoginsengresult+=Digit; - } the Else + { A if(flag==1)returnInt_max; the Else returnint_min; + } - $str++; $ } - - returnflag*result; the } -};
"Leetcode" String to Integer (atoi)