题目描述
请你写一个函数StrToInt,实现把字符串转换成整数这个功能。当然,不能使用atoi或者其他类似的库函数。
算法分析
考虑边界条件,数据上下溢出、空字符串、只有正负号、有无正负号、错误标志输出等;0值和无效输入之间的区分加个标志位即可,由于牛客网没有对该项做要求,加之作者偷懒,就没写了。
提交代码:
class Solution {
public:
int StrToInt(string str)
{
if (str.empty())
return 0;
int i = 0, result = 0;
bool minus = false;
if (str[i] == '+')
++i;
else if (str[i] == '-')
{
++i;
minus = true;
}
if (i < str.size())
result = StrToIntCore(str, i, minus);
return (int)result;
}
long long StrToIntCore(string &str, int index, bool minus)
{
long long result = 0;
while (index < str.size())
{
if (str[index] >= '0' && str[index] <= '9')
{
int flag = minus ? -1 : 1;
result = result * 10 + flag * (str[index] - '0');
// 溢出判断
if ((!minus && result > numeric_limits<int>::max())
|| (minus && result < numeric_limits<int>::min()))
{
result = 0;
break;
}
++index;
}
else
{
result = 0;
break;
}
}
return result;
}
};
测试代码:
// ====================测试代码====================
void Test(const string string)
{
Solution s;
int result = s.StrToInt(string);
if (result == 0)
cout << "the input " << string <<" is invalid.\n";
else
cout<< "number for " << string << " is: " << result << ".\n";
}
int main(int argc, char* argv[])
{
Test(string());
Test("");
Test("123");
Test("+123");
Test("-123");
Test("1a33");
Test("+0");
Test("-0");
//有效的最大正整数, 0x7FFFFFFF
Test("+2147483647");
Test("-2147483647");
Test("+2147483648");
//有效的最小负整数, 0x80000000
Test("-2147483648");
Test("+2147483649");
Test("-2147483649");
Test("+");
Test("-");
return 0;
}