题解 | #把字符串转换成整数#
把字符串转换成整数
http://www.nowcoder.com/practice/1277c681251b4372bdef344468e4f26e
class Solution {
public:
int StrToInt(string str) {
int size = str.size();
if (size == 0)
return 0;
int res = 0;
char temp = str[0];
int flag = 1;
int start = 0;
if (temp == '+' || temp == '-') {
start = 1;
if (temp == '+')
flag = 1;
else
flag = -1;
}
for (int i = start; i < size; ++i) {
if (str[i] - '0' > 9 || str[i] - '0' < 0) {
return 0;
}
else {
res = 10 * res + flag * (str[i] - '0');
}
}
return res;
}};
查看7道真题和解析