题解 | #把字符串转换成整数#
把字符串转换成整数(atoi)
https://www.nowcoder.com/practice/d11471c3bf2d40f38b66bb12785df47f?tpId=265&rp=1&ru=%2Fexam%2Foj%2Fta&qru=%2Fexam%2Foj%2Fta&sourceUrl=%2Fexam%2Foj%2Fta%3FjudgeStatus%3D3%26page%3D1%26pageSize%3D50%26search%3D%26tpId%3D13%26type%3D265&difficulty=&judgeStatus=3&tags=&title=&gioEnter=menu
状态有点麻木,不该熬夜的。
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @return int整型
*/
int StrToInt(string s) {
if (s.empty()) {
return 0;
}
int res = 0;
int sign = 1;
int index = 0;
while (index < s.size()) {
if (s[index] == ' ') {
++index;
} else {
break;
}
}
// 只有空格
if (index == s.size()) {
return 0;
}
if (s[index] == '-') {
sign = -1;
++index;
} else if (s[index] == '+') {
++index;
}
// 只有符号
if (index == s.size()) {
return 0;
}
while (index < s.size()) {
char c = s[index];
if (c < '0' || c > '9') {
break;
}
// 溢出判断
if (res > INT_MAX / 10 || (res == INT_MAX / 10 && (c - '0') > INT_MAX % 10)) {
return INT_MAX;
}
if (res < INT_MIN / 10 || (res == INT_MIN / 10 && (c - '0') < INT_MIN % 10)) {
return INT_MIN;
}
res = res * 10 + sign * (c - '0');
++index;
}
return res;
}
};