题解 | #把字符串转换成整数#
把字符串转换成整数
https://www.nowcoder.com/practice/1277c681251b4372bdef344468e4f26e
#include <string>
class Solution {
public:
int StrToInt(string str) {
int ans=0;
int cnt=0;
if(str[0]=='+')
str.erase(0, 1);
for(int i=str.size()-1;i>=0;i--)
{
if((str[i]>='0'&&str[i]<='9')||str[i]=='-')
{
if(str[i]=='-')
return -ans;
ans=(str[i]-'0')*pow(10,cnt++)+ans;
}
else
return 0;
}
return ans;
}
};