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.
首先,字符串开始的空白字符要跳过,并且需要记录首字母是‘+’‘-’或者直接就是数字,以此来判断正负数。
其次,对于转换结果,我们知道整型数据的范围是INT_MIN(-2147482648)到INT_MAX(2147483647),超出范围则返回最大与最小值。所以我们可以开始用long long类型的变量存储结果;
class Solution {
public:
int myAtoi(string str) {
if(str.size()==0)
return 0;
long long res=0;
int flag=1;
int i=0;
while(str[i]==' ')
i++;
if(str[i]=='+')
i++;
else if(str[i]=='-'){
flag=-1;
i++;
}
for(int j=i;j<str.size();j++)
{
if(str[j]<='9'&&str[j]>='0')
{
res=res*10+(str[j]-'0');
if(res>INT_MAX)
return flag>0?INT_MAX:INT_MIN;
}
else
break;
}
return res*flag;
}
};