class Solution {
public:
int myAtoi(string str) {
int len = str.length();
int index = 0;
long long num = 0;
bool start = false;
int sym = 1;
while (index < len) {
if (start == false && str[index] == ' ') {
index++;
continue;
}
if ((start == false && (str[index] == '-' || str[index] == '+')) || ('0' <= str[index] && str[index] <= '9')) {
if (str[index] == '-')
sym = -1;
if ('0' <= str[index] && str[index] <= '9') {
if (!start) {
num = str[index] - 48;
}
else {
num *= 10;
num += (str[index] - 48);
if (num * sym < 0 && num > 2147483648)
return -2147483648;
if (num * sym > 0 && num > 2147483647)
return 2147483647;
}
}
if (start == false)
start = true;
}
else {
if (start)
break;
else
return 0;
}
index++;
}
return num * sym;
}
};
LetCode 8. 字符串转整数 (atoi)
最新推荐文章于 2024-09-29 19:46:50 发布