int atoi(const char *str) {
int beg = 0, end = strlen(str)  1;
long long int num = 0;
bool negative = false;
for(int i = beg; i <= end ;i++)
if(str[i] == ' ') beg++;
else break;
for(int i = end; i >= 0; i)
if(str[i] == ' ') end;
else break;
//there will be only one sign (plus or minus)
if(str[beg] == '') { beg++; negative = true;}
else if(str[beg] == '+') beg++;
for(int i = beg; i <= end; i++){
int tmp = str[i]  '0';
if(tmp > 9  tmp < 0)
if(num != 0) break;//already have a converted integer. Ex: " 0012a42" > 12
else return 0;//there's still invalid character
num = (num * 10) + tmp;
if(!negative && num > 2147483647)//out of range
return INT_MAX;
else if(negative && num > 2147483648)//out of range, right now, num > 0
return INT_MIN;
}
if(negative)
return num;
return num;
}
My C++ clear but little long code in O(n) time complexity


Thanks for your post. However it would be better to share solution with correct code format and elaborated thoughts. Please read the Discuss FAQ for more info. Take a look at good sharing example
Pay attention to "Writing code? Select all code then click on the {} button to preserve code formatting.” above text editor.