您的位置:首页 > 职场人生

面试题49:把字符串转换成整数(atoi)

2016-07-21 16:54 316 查看
需要考虑的问题都已在程序中注释

bool isValid;

int StrToInt(const char* str)
{
isValid = false;
//不合法情形1:空指针
if (str == NULL)
return 0;

//不合法情形2:内容为“”
if (*str == '\0')
return 0;

const char *pData = str;
bool isNegative = false;
if (*pData == '+')
{
isNegative = false;    //是否是负数
pData++;
//不合法情形3:内容为+
if (*pData == '\0')
return 0;
}
else if (*pData == '-')
{
isNegative = true;
pData++;
//不合法情形3:内容为-
if (*pData == '\0')
return 0;
}

long long num = 0;    //设为long long检查越界
while (*pData != '\0')
{
//不合法情形5:存在非数字
if (*pData < '0' || *pData > '9')
return 0;
else
{
num = num * 10 + (*pData - '0');
}
pData++;
}

//不合法情形6:越界
num = isNegative ? 0 - num : num;
//注意一定要加(signed int)
if (isNegative && num < (signed int)0x80000000 || !isNegative && num > 0x7FFFFFFF)
return 0;

isValid = true;
return num;
}


带测试的完整代码:

#include<iostream>
using namespace std;

bool isValid;

int StrToInt(const char* str)
{
isValid = false;
//不合法情形1:空指针
if (str == NULL)
return 0;

//不合法情形2:内容为“”
if (*str == '\0')
return 0;

const char *pData = str;
bool isNegative = false;
if (*pData == '+')
{
isNegative = false;    //是否是负数
pData++;
//不合法情形3:内容为+
if (*pData == '\0')
return 0;
}
else if (*pData == '-')
{
isNegative = true;
pData++;
//不合法情形3:内容为-
if (*pData == '\0')
return 0;
}

long long num = 0;    //设为long long检查越界
while (*pData != '\0')
{
//不合法情形5:存在非数字
if (*pData < '0' || *pData > '9')
return 0;
else
{
num = num * 10 + (*pData - '0');
}
pData++;
}

//不合法情形6:越界
num = isNegative ? 0 - num : num;
//注意一定要加(signed int)
if (isNegative && num < (signed int)0x80000000 || !isNegative && num > 0x7FFFFFFF)
return 0;

isValid = true;
return num;
}

void Test(const char *testNum)
{
int result = StrToInt(testNum);
if (testNum == NULL)
{
cout << "char * is Null" << endl;
cout << "input is not vaild" << endl;
cout << endl;
return;
}
cout << "Test string is: " << testNum << endl;
if (isValid)
cout << result << endl;
else
cout << "input is not vaild" << endl;
cout << endl;

}

int main()
{
Test(NULL);

Test("");

Test("123");

Test("+123");

Test("-123");

Test("1a33");

Test("+0");

Test("-0");

Test("+");

Test("-");

//有效的最大正整数, 0x7FFFFFFF
Test("+2147483647");

Test("-2147483647");

Test("+2147483648");

//有效的最小负整数, 0x80000000
Test("-2147483648");

Test("+2147483649");

Test("-2147483649");

system("pause");

return 0;
}


View Code

itoa实现,最后别忘加='\0'

void itoa(int num, char *str)
{
int power = 1;
int j = num;

while (j / 10 != 0)
{
power *= 10;
j /= 10;
}

while (num != 0)
{
*str++ = '0' + (num / power);
num %= power;
power /= 10;
}
*str = '\0';
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: