把字符串转换成整数
1.不考虑溢出也能过[牛客测试不全面]
class Solution
{
public:
int StrToInt(string str)
{
int answer = 0;
int isplus = 1;
for (char& ch : str)
{
if (ch == '+')
isplus = 1;
else if (ch == '-')
isplus = - 1;
else
{
if (ch < '1' || ch > '9')
return 0;
else
answer = answer * 10 + ch - '0';
}
}
return isplus * answer;
}
};
2.考虑溢出
class Solution
{
public:
int StrToInt(string str)
{
int len = str.size();
if (len == 0)
return 0;
int answer = 0;
int flag = 1;
for (char& ch : str)
{
if (ch == '+')
flag = 1;
else if (ch == '-')
flag = -1;
else
{
if (ch < '1' || ch > '9')
return 0;
else
{
answer = answer * 10 + ch - '0';
if (
(flag == 1 && answer > 0x7fffffff)
|| (flag == -1 && answer > 0x80000000)
)
return 0;
}
}
}
return flag * answer;
}
};