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.
Update (2015-02-10):
The signature of the C++
function had been updated. If you still see your function signature accepts a const char *
argument, please click on the reload button to reset your code Definition.
Test instructions: Change a string that matches a condition to a number
Difficulty: This problem is not difficult, it is difficult to consider the conversion conditions
1. Consecutive numeric characters
2. Consecutive numeric characters cannot be preceded by ' + ', '-', characters other than, and the minus sign is connected to the number
3. Consecutive numeric characters can be followed by subtitles (I don't know why this is possible)
4. Consider overflow
1 intMyatoi (Char*str) {2 intlen,i;3len=strlen (str);4 Longtmp=0;5 intflag=0;6 for(i=0; i<len;i++)7 {8 while(str[i]==' ')9i++;Ten if(str[i]=='+') One { Aflag=1; -i++; - } the Else if(str[i]=='-') - { -flag=-1; -i++; + } - if(flag&&! (str[i]<='9'&&str[i]>='0')) + return 0; A while(i<len&& (str[i]<='9'&&str[i]>='0')) at { - if(tmp<0) -tmp=tmp*Ten-(str[i]-'0'); - Else -tmp=tmp*Ten+ (str[i]-'0'); - if(-1==flag) in { -tmp*=-1; to if(tmp<0) +flag=1; - } the if(tmp>Int_max) * return 2147483647; $ Else if(tmp<int_min)Panax Notoginseng return-2147483648; -i++; the } + while(i<len) Ai++; the } + returntmp; -}
"Leetcode" 8. String to Integer (atoi)