题解 | #将字符串转化为整数#
将字符串转化为整数
http://www.nowcoder.com/practice/44d8c152c38f43a1b10e168018dcc13f
public:
int atoi(const char *str) {
int n = 0,result = 0;
bool positive= true;
if(str==NULL)
return -1;
while(*(str+n)!=NULL)
{
if(*(str+n)>='0'&&*(str+n) <='9')
{
result = result*10 + *(str+n) - '0';
}
else if(result!=0)
{
return result*(positive) -result*(!positive);
}
else if(*(str+n) =='-')
{
positive=!positive;
}
n++;
}
return result*(positive) -result*(!positive);
}
};