题解 | #把字符串转换成整数#
把字符串转换成整数
https://www.nowcoder.com/practice/1277c681251b4372bdef344468e4f26e
class Solution { public: int StrToInt(string str) { if (str == "") return 0; long long res = 0; bool up = true; int i = 0; if (str[i] == '+' || str[i] == '-') { if (str[i] == '-') up = false; i++; } for (; i < str.length(); i++) { if (str[i] >= '0' && str[i] <= '9') { res = res * 10 + str[i] - '0'; if (up && res >= INT_MAX) return INT_MAX; if (!up && (-res <= INT_MIN)) return INT_MIN; } else return 0; } return up? res: -res; } };