题目要求: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.
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 the reload button to reset your code definition.
spoilers alert... click to show requirements for atoi.
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, 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 effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be 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 returned.
题目希望答题者在没有给出具体的要求,只说明让把string转换为int型的情况下,考验答题者能不能够全面去考虑这道题,只要把各方面考虑到这道题其实不难。
下面是我总结的几个考察点:
- 输入为空字符串时;
- 字符串前有空格时;比如“ 324132”
- 字符串前有+-号的时候,主要不能出现+-好只能出现一个,并只能出现一次,根据其确定输出是正数还是负数;
- 越界问题,我的代码里用的是我自己的土办法,当然也可以把result定义long long类型,然后直接用起与max=0x7fffffff或min=0x80000000;
- 当读取时中间突然输入一个非数字字符,则返回已读到的数字;比如1234a123;
- 当越上界则返回上届0x7fffffff,当越下界时则返回下界0x80000000
class Solution {
public:
int myAtoi(string str)
{
int l=str.length();
if(l==0)
{
return 0;
}
int result=0;
int i=0,a=1;//a用来标记正负
bool first=false;
while(str[i]==' ')
{
i++;
}
while(str[i]=='+'||str[i]=='-')//用来确认有几个+-符号,如果超过一个则返回0
{
if(str[i]=='+')
{
if(first) //如果是第二个+-号,则返回0
{
return 0;
}
first=true;
}
else if(str[i]=='-')
{
if(first)
{
return 0;
}
first=true;
a=-1;
}
i++;
}
while(str[i]!='\0')
{
if(str[i]<'0'||str[i]>'9')
return result;//如果出现非数字符号,则返回当前读取的数字
if(result>214748364||(result==214748364&&(str[i]-'0')>7))//越上界
{
return 2147483647;//如果越界则返回最大int值
}
else if(result<-214748364||(result==-214748364&&(str[i]-'0')>8))//越下界
{
return -2147483648;//如果越界则返回最小int值
}
result=result*10+a*(str[i]-'0');//a标记的是正负号
i++;
}
return result;
}
};