把字符串转换成整数加粗样式## 标题
题目:写一个StrToInt,实现字符串转换成整数的功能,不使用atoi或其他类似的库函数。
enum Status{kValid=0,kInvalid};
int g_nStatus = kValid;
long long StrToCore(const char* digit, bool minus)
{
long long num = 0;
while (*digit != '\0')
{
if (*digit >= '0'&&*digit <= '9')
{
int flag = minus ? -1 : 1; //正数或负数
num = num * 10 + flag*(*digit - '0');
if (!minus&&num > 0x7FFFFFFF || (minus&&num < (signed int)0x80000000))// 考虑上下溢出
{
num = 0;
break;
}
digit++;
}
else
{
num = 0;break;
}
}
if (*digit == '\0')
{
g_nStatus = kValid;
}
return num;
}
int StrToInt(const char* str)
{
g_nStatus = kInvalid;
long long num = 0;
if (str != NULL&&*str != '\0') // 考虑空指针和空字符串
{
bool minus = false;
if (*str == '+') //考虑输入的是“+”,“-”符号(正负号)
str ++;
else if (*str == '-')
{
str++;
minus = true;
}
if (*str != '\0')
{
num = StrToCore(str, minus);
}
}
return (int)num;
}
int main()
{
char wer0[] = { "9434644" };
char wer1[] = { "-9434644" };
char wer2[] = { "+" };
char wer3[] = { "-" };
char wer4[] = { "sdg" };
char wer5[] = { "36843154648824346544632" };
cout<<"字符串转换为数字为:"<<StrToInt(wer0)<<endl;
cout<<"字符串转换为数字为:"<<StrToInt(wer1)<<endl;
cout<<"字符串转换为数字为:"<<StrToInt(wer2)<<endl;
cout<<"字符串转换为数字为:"<<StrToInt(wer3)<<endl;
cout<<"字符串转换为数字为:"<<StrToInt(wer4)<<endl;
cout<<"字符串转换为数字为:"<<StrToInt(wer5)<<endl;
Sleep(1000000000);
}