题目传送门
链接:https://leetcode-cn.com/problems/string-to-integer-atoi/
题干
题解
题意为先检测前导空格,再检测正负号,再检测数字,最后检测非数字字符。最后根据正负号和数字字符,来输出答案。
需要注意的是空格、正负号、数字都可能没有,有可能第一个字符就是非数字字符,那么就要直接停止,直接输出0。
看到了题解用python正则表达式可以一行解决QAQ
下面的代码是C语言的暴力做法
Code
class Solution {
public:
int myAtoi(string s) {
long long res = 0;
bool start = false; // 表示是否开始记录数字
int sign = 1; // 符号位
for (char c : s) {
// 未开始记录数字
if (start == false) {
if (c == ' ') {
continue;
} else if (c == '-') {
sign = -1;
start = true;
} else if (c == '+') {
sign = 1;
start = true;
} else if (isdigit(c)) {
start = true;
res = sign * (c - '0');
} else {
return res;
}
} else { // 开始记录数字
if (isdigit(c)) {
res = res * 10 + sign * (c - '0');
if (res > INT_MAX)
return INT_MAX;
else if (res < INT_MIN)
return INT_MIN;
} else {
return res;
}
}
}
return res;
}
};