8.String to Integer(atoi)
思路:
- 细节题,应该不断和面试官交流确定一些特殊情况。
class Solution {
public:
int myAtoi(string str) {
int num = 0;
int sign = 1;
int i;
for(i = 0; i < str.length(); i++){
if(str[i] == ' ') continue;
else break;
}
if(str[i] == '+') i++;
else if(str[i] == '-') {
sign = -1;
i++;
}
for(; i < str.length(); i++){
if(str[i] > '9' || str[i] < '0') break;
else{
if(num > INT_MAX / 10 || (num == INT_MAX/10 && str[i] - '0' > INT_MAX % 10)) return sign == -1 ? INT_MIN : INT_MAX;
else{
num = num*10 + str[i] - '0';
}
}
}
return num*sign;
}
};