输入一个字符串,包括数字字母符号,可以为空
如果是合法的数值表达则返回该数字,否则返回0
class Solution { public: int StrToInt(string str) { if(str.empty()||str=="0") return 0; int res=0; int flag=str[0]==‘-‘?-1:1; for(int i=(str[0]==‘+‘||str[i]==‘-‘?1:0);i<str.size();++i) { if(str[i]<‘0‘||str[i]>‘9‘) return 0; res=(res<<1)+(res<<3)+(str[i]&0xf); } return res*flag; } };
原文:https://www.cnblogs.com/tianzeng/p/11397544.html