您的位置:首页 > 其它

Facebook :实现atoi函数

2015-07-28 21:39 260 查看
一、
class CException
{
public:
CException(const char* str) : m_strErr(str) {}
string GetErrInfo() { return m_strErr; }
private:
std::string m_strErr;
};

int myatoi(const char* p)
{
assert(p);

int nFlg = 1;
if ('-' == *p)
nFlg = -1;

if ('-' == *p || '+' == *p)
p++;

if ('\0' == *p)
throw CException("Invalid expression");

int nRet = 0;
while('\0' != *p)
{
if (*p < '0' || *p > '9')
throw CException("Invalid character");

int nVal = *p - '0';
int nNew = nRet*10 + nFlg * nVal;
if (nRet != 0 && ((nNew & 0x80000000) != (nRet & 0x80000000)))
throw CException("Integer over flow");

nRet = nNew;
p++;
}

return nRet;
}

二、

int atoi (char* str)
{
assert(str);
assert(str[0]);
int result = 0;
int newResult = 0;
if (str[0] == '+')
return atoi(str + 1);
if (str[0] == '-')
return -1 * atoi(str + 1);

int i = 0;

while (str[i])
{
assert(str[i] >= '0' && str[i] <= '9');
newResult = (result << 1) + (result << 3) + str[i] - '0';
assert(newResult >= result);
result = newResult;
i++;
}

return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: