题解 | #c++ 这个题较难?? 9 行搞定,还可以优化 #
把字符串转换成整数
http://www.nowcoder.com/practice/1277c681251b4372bdef344468e4f26e
/*首先,这个题不考虑字母*/
/*那就简单多了,只考虑数字,遇到其他情况直接返回-1就行了*/
class Solution {
public:
int StrToInt(string str) {
int ans = 0;int isplus = 1;
for(char ch:str){
if(isalpha(ch)){
return 0;
}if (ch == '+' || ch =='-'){
isplus = (ch == '+') ? 1 : -1;
}if(isdigit(ch)){
ans = ans*10+ch-'0';
}
}return isplus*ans;
}
};