您的位置:首页 > 其它

字符串转为int类型

2015-08-30 10:03 351 查看
题目:

字符串转为int类型

解析:

题目比较简单,重要的是要思考全面,所以这里不过多赘述

注意:

1 判断字符串是否为空

2 判断正负号

3 判断字符串转换是否超出int类型表示范围

4 如果转换出错,返回什么(博客中返回0,设置标志位,判断0是正常返回0,还是转换出错返回0)

算法实现:

enum Status {KVilid = 0,KInVilid};
Status gStatus = KVilid;

int StrToInt(const char* str)
{
gStatus = KInVilid;
long long int num = 0;

//如果字符串为空,则返回0,gStatus标识设为KInVilid
if(nullptr == str || strlen(str) < 1)
{
return static_cast<int>(num);
}

const char* digit = str;
bool minus = false;

//判断正负号
if('+' == *digit)
{
++digit;
}
else if('-' == *digit)
{
minus = true;
++digit;
}

//str转换为数字
while('\0' != *digit)
{
//如果字符串内字符不合法,则num设为0,gStatus设为KInVilid
if(*digit > '9' || *digit < '0')
{
num = 0;
break;
}

num = num * 10 + (*digit - '0');

//判断是否超出int表示范围
if(num > std::numeric_limits<int>::max())
{
num = 0;
break;
}
++digit;
}

if('\0' == *digit)
{
gStatus = KVilid;
if(minus)
{
num = 0 - num;
}
}
return static_cast<int>(num);
}


算法测试代码:

#include <iostream>

using namespace std;

enum Status {KVilid = 0,KInVilid}; Status gStatus = KVilid; int StrToInt(const char* str) { gStatus = KInVilid; long long int num = 0; //如果字符串为空,则返回0,gStatus标识设为KInVilid if(nullptr == str || strlen(str) < 1) { return static_cast<int>(num); } const char* digit = str; bool minus = false; //判断正负号 if('+' == *digit) { ++digit; } else if('-' == *digit) { minus = true; ++digit; } //str转换为数字 while('\0' != *digit) { //如果字符串内字符不合法,则num设为0,gStatus设为KInVilid if(*digit > '9' || *digit < '0') { num = 0; break; } num = num * 10 + (*digit - '0'); //判断是否超出int表示范围 if(num > std::numeric_limits<int>::max()) { num = 0; break; } ++digit; } if('\0' == *digit) { gStatus = KVilid; if(minus) { num = 0 - num; } } return static_cast<int>(num); }
void TestStrToInt(const char *str,int n)
{
if(gStatus == KVilid)
{
cout<<"str ="<<str<<" int = "<<n<<endl;
}
else
{
if(nullptr != str && strlen(str) >= 1)
{
cout<<"error ,can't translate str:"<<str<<" to Int"<<endl;
}
else
{
cout<<"error, str is null"<<endl;
}
}
}

int main()
{
const char* str1 = "";
const char* str2 = nullptr;
const char* str3 = "10000000000000000";
const char* str4 = "+100000000";
const char* str5 = "-100";
const char* str6 = "+1000000000000000";
const char* str7 = "-1000000000000000";

TestStrToInt(str1,StrToInt(str1));
TestStrToInt(str2,StrToInt(str2));
TestStrToInt(str3,StrToInt(str3));
TestStrToInt(str4,StrToInt(str4));
TestStrToInt(str5,StrToInt(str5));
TestStrToInt(str6,StrToInt(str6));
TestStrToInt(str7,StrToInt(str7));

return 0;
}


运行结果:

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