8. String to Integer (atoi)
class Solution {
public:
int myAtoi(string str) {
int Max = (1<<31)-1, Min = -1<<31;
int i = 0;
int minus = 1;
while(str[i] == ' ') i++;
if(str[i] == '-'){
minus = -1;
i++;
}
else if(str[i] == '+') i++;
if(!isdigit(str[i])) return 0;
int j = i;
while(isdigit(str[j])) j++;
j--;
int n = 0;
for(int k = 0;i + k <= j;k++){
n += pow(10,k)*(str[j-k]-'0');
if(n < 0) return minus == -1 ? Min : Max;
}
return minus*n;
}
};
Email:JingwangLi@outlook.com