题解 | #把字符串转换成整数#
把字符串转换成整数
https://www.nowcoder.com/practice/1277c681251b4372bdef344468e4f26e
class Solution { public: int StrToInt(string str) { int result= 0 ; int flag =1 ; for(auto ch : str) { //有字母 if( isalpha(ch) ) //Check if character is alphabetic { return 0 ; } // + 不影响结果 if(ch =='+' || ch == '-' ) { flag = ch=='+' ? 1 : -1; } //数字 if(isdigit(ch)) { result = result *10 + ch-'0';//将字符转换为整数,并且结果向左移动一位 } } return flag * result; } };