class Solution {
//note:
//1. NULL
//2. sign
//3. prefix ' '
//4. out of range, to avoid this we use long long
public:
int atoi(const char *str) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(str == NULL) return 0;//NULL
while (*str == ' ')//prefix ' '
str++;
int sign = 1;
if(*str == '-')//sign '+' or '-'
{
sign = -1;
str++;
}
else if(*str == '+')
str++;
long long ans = 0;
while (*str >= '0' && *str <= '9')
{
ans = ans*10+*str-'0';
if(ans > INT_MAX)//out of range
return sign < 0 ? INT_MIN : INT_MAX;
str++;
}
ans *= sign;
return (int)ans;
}
};
second time
class Solution {
public:
int atoi(const char *str) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(str == NULL) return 0;
bool sign = true;
while (*str == ' ')//prefix ' '
str++;
if(*str == '+' || *str == '-')
{
if(*str == '+') sign = true;
else sign = false;
str++;
}
long long ans = 0;
while(*str >= '0' && *str <= '9')
{
ans = ans*10+(*str-'0');
if(ans > INT_MAX) return sign == true ? INT_MAX : INT_MIN;
str++;
}
if(sign == false) return (int)(-ans);
else return (int)ans;
}
};