Question:
Implement Atoi to convert a string to a integer.
Hint:carefully consider all possible input cases. If you are want a challenge, please don't be below and ask yourself what are input possible.
Notes:it is intended for this problem to be specified vaguely (ie, no given input specs). You are are responsible to gather all of the input requirements up front.
Requirements for Atoi:
The function A-discards as many whitespace characters as necessary until the ' the ' non-whitespace is character. Then, starting from this character, takes a optional initial plus or minus sign followed by as many numerical as P Ossible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no Effe CT on the behavior's this function.
If the sequence of non-whitespace characters in Str are not a valid integral number, or if no such sequence Cause either str is empty or it contains only whitespace characters, no conversion is performed.
If No valid conversion could are 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 main idea is to convert the string into a number, but I see this problem through the rate is very low, but it is Eazy problem, and later found that is due to pay attention to a lot of special circumstances algorithm:
1, the number of the first character can only be ' + ', '-', digital
2, if the character from the first character is not a number, that is, before returning the number
3, if the first character is '-' then return a negative number
4, if the int number overflow that returns Int_max (positive) or int_min (negative) submitted Code:
Class Solution { ///The first number must be ' + ' or '-' or number followed by a number that is not in 0~9, return directly to the preceding number public
:
int myatoi (string str) {
if (Str.empty ()) return 0;
Long long int res=0;
int flag=1; Flag is positive and negative sign bit
int i=0,j=0;
while (str[i] = = ")
i++;
if (str[i] = = ' + ')
i++;
else if (str[i] = = '-')
{
i++;
flag =-1;
}
j=i;
For (J=i;j<str.size (); j + +)
{
if (str[j]>= ' 0 ' && str[j]<= ' 9 ')
{
res=res*10+ ( str[j]-' 0 ');
if (Res>int_max) return
flag>0? int_max:int_min;
}
else if (str[j]< ' 0 ' | | str[j]> ' 9 ') return
flag>0 Res: ( -1) *res;
}
Return Flag==1?res: ( -1) *res;
}
;