题目
Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
这个的情况和常见的atoi有点不一样,会跳过开头的空格,但是不会跳过出现正负号或则数字后的空格
代码:
class Solution {
public:
int atoi(const char *str) {
if(*str=='\0')
return false;
long long ans=0;
int flag=1;
while(*str==' ')
str++;
if(*str=='+')
str++;
else if(*str=='-')
{
flag=-1;
str++;
}
while(isdigit(*str))
{
ans=ans*10+*str++-'0';
if(flag==1&&ans>=INT_MAX)
return INT_MAX;
else if(ans>INT_MAX)
return INT_MIN;
}
return ans*flag;
}
};