实现atoi()函数 C/C++
class Solution {
public:
int atoi(const char *str) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int flag = 0;
int plus=0;
bool tozero=false;
int sum = 0;
int sum_num=0;
for( const char *p = str; *p != '\0'; ++p )
{
if( *p =='-' )
{
flag++;
if(flag==2)
{
break;
}
}
else if(*p == '+')
{
plus++;
if(plus==2)
{
break;
}
}
else if( *p >='0'&& *p <='9' )
{
if(sum_num==10)
{
if(flag==1)
return 0x7fffffff+1;
else
return 0x7fffffff;
}
if( (sum * 10) == 2147483640 )
{
if(flag != 1 && (*p-'0') >= 7)
{
sum=0x7fffffff;
return sum;
}
else if(flag == 1 && (*p - '0') >= 8 )
{
sum=0x7fffffff;
sum++;
return sum;
}
}
sum = sum * 10 + ( *p - '0' );
sum_num++;
}
else if(*p == ' '&& plus==0 && flag==0)
{
if(sum!=0)
{
break;
}
}
else
{
break;
}
}
if(flag==1)
{
sum=-sum;
}
return sum;
}
};