题目:
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.
就是把字符串改成整数,注意‘+’和空格,以及溢出情况
代码:
class Solution {
public:
int myAtoi(string str) {
int n = str.size();
int p = 0;
int z = 1;
long long temp = 0;
while(str[p] == ' ')
p++;
if(str[p] == '+' || str[p] == '-')
{
if(str[p] == '-')
z = -1;
p++;
}
for(int i = p; i < n;i ++)
{
if(str[i] >= '0' && str[i] <= '9')
{
temp = temp*10 + str[i]- '0';
if(z * temp < INT_MIN)
return INT_MIN;
if(z * temp > INT_MAX)
return INT_MAX;
}
else
break;
}
return z * temp;
}
};