题解 | 把字符串转换成整数
把字符串转换成整数
https://www.nowcoder.com/practice/1277c681251b4372bdef344468e4f26e
class Solution {
public:
int StrToInt(string str) {
if(str.empty())
{
return 0;
}
string s2;
int sign = 1; // 符号位(1正,-1负)
int index = 0; // 遍历指针
if(str[index]=='+'||str[index]=='-')
{
sign=(str[index]=='+')?1:-1;
index++;
if(index>=str.length())return 0;
}
while(index<str.size())
{
if(str[index]>='0'&&str[index]<='9')
{
s2.push_back(str[index]);
}
else {
return 0;
}
index++;
}
long result=0;
//范围for强转数字
for(auto ch:s2)
{
result=result*10+(ch-'0');
}
return sign*result;
}
};
查看22道真题和解析