AC代码
class Solution {
private:
int MAX_INT = 2147483647;
int MIN_INT = -2147483648;
public:
int myAtoi(string str) {
str = trim(str);
//
int n = str.size();
if(n <= 0) {
return 0;
}
//使用long long防止结果越界
long long result = 0;
bool isNeg = false;//false表示正数,true表示负数
int start = 0;
//负数
if(str[0] == '-') {
isNeg = true;
start++;
} else if(str[0] == '+') {
start++;
}
int i;
int end = findEnd(start, str);
//是否超出int范围
bool outOf = isOutOfRnage(start, end, str);
if(outOf) {
if(isNeg) {
return MIN_INT;
} else {
return MAX_INT;
}
}
for(i = start; i < end; i++) {
//
if(!isDigit(str[i])) {
return result;
}
result += (str[i] - '0') * power(10, end - i - 1);
}
if(isNeg) {
result = -result;
}
//判断是否超界
if(result < MIN_INT) {
return MIN_INT;
} else if(result > MAX_INT) {
return MAX_INT;
} else {
return result;
}
}
int power(int base, int exp) {
if(exp < 0) {
return 0;
} else if(exp == 0) {
return 1;
} else {
int result = 1;
while(exp > 0) {
result *= base;
exp--;
}
return result;
}
}
bool isDigit(char c) {
if(c >= '0' && c <= '9') {
return true;
} else {
return false;
}
}
//去掉两边的空格
string trim(string str) {
int i,n;
n = str.size();
int start = 0;
int end = n - 1;
for(i = 0; i < n; i++) {
if(str[i] != ' ') {
break;
}
start++;
}
for(i = n - 1; i >= 0; i--) {
if(str[i] != ' ') {
break;
}
end--;
}
if(start > end) {
return "";
} else {
return str.substr(start, end - start + 1);
}
}
int findEnd(int start, string str) {
int i;
int n = str.size();
for(i = start; i < n; i++) {
if(!isDigit(str[i])) {
break;
}
}
return i;
}
bool isOutOfRnage(int start, int end, string str) {
if(end - start > 10) {
return true;
}
if(end - start == 10 && str[start] > '2') {
return true;
}
return false;
}
};