这是一道面试的时候,面试官经常喜欢考察的一道题目,因为这考察了很多方面的东西, 对输入的字符串的处理, 异常的处理, 溢出时候处理。下面是我自己实现的代码,仅供参考,如果有什么问题欢迎留言。
代码:
int atoi(const char* str)
{
if(NULL == str)
throw std::exception("NULL pointer.");
size_t len = strlen(str);
if(len == 0)
throw std::exception("Empty input.");
bool is_positive = true;
size_t begin = 0;
if(str[begin] == '-')
{
++begin;
is_positive = false;
}
else if(str[begin] == '+')
++begin;
int flag = 1;
if(!is_positive)
flag = -1;
long long res = 0;
for(size_t i = begin; i < len; ++i)
{
if(!(str[i] >= '0' && str[i] <= '9'))
throw std::exception("Invalid input.");
res = 10 * res + flag *(str[i] - '0');
if(res > numeric_limits<int>::max() || res < numeric_limits<int>::min())
throw std::exception("Overflow");
}
return static_cast<int>(res);
}