### leetcode Question 103: String to Integer (atoi)

String to Integer (atoi)

Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

Analysis:
As there is no need to consider float number, what we need concern here is
(1) "+" and "-"
(2) The boundary INT_MAX and INT_MIN
(3) Eliminate the spaces before.
(4) Meet non-digit after digit then return.

### Code(Updated 201309):

class Solution {
public:
int atoi(const char *str) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (!str){return 0;}
int i=0;
bool pos=true;
int res=0;
while (str[i]==' '){ i++;}
if (str[i]=='+'){ pos=true;i++;}
if (str[i]=='-'){ pos = false;i++;}
if (!isdigit(str[i])){return 0;}
while (isdigit(str[i])){
if (pos && res>INT_MAX/10){return INT_MAX;}
if (pos && res==INT_MAX/10 && int(str[i]-'0')>=7){return INT_MAX;}
if (!pos && -res<INT_MIN/10){return INT_MIN;}
if (!pos && -res==INT_MIN/10 && int(str[i]-'0')>=8){return INT_MIN;}
res = res*10 + int(str[i]-'0');
i++;
}

if (pos){return res;}
else{return -res;}

}
};