string to integer (implement atoi) Implement atoi to convert a string to an integer.
  
  Requirements for atoi: The function first discards as many whitespace
  characters as necessary until the first non-whitespace character is
  found. Then, starting from this character, takes an optional initial
  plus or minus sign followed by as many numerical digits as possible,
  and interprets them as a numerical value.
  
  The string can contain additional characters after those that form the
  integral number, which are ignored and have no effect on the behavior
  of this function.
  
  If the first sequence of non-whitespace characters in str is not a
  valid integral number, or if no such sequence exists because either
  str is empty or it contains only whitespace characters, no conversion
  is performed.
  
  If no valid conversion could be performed, a zero value is returned.
  If the correct value is out of the range of representable values,
  INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.


The following is my code:

int atoi(const char *str) {
    int sign = 1;
    long long i = 0, j = 0;

    while ((*str) != '\0' &amp;&amp; isspace(*str)) {
        ++str;
    }

    if (((*str)!='\0') &amp;&amp; ((*str) == '+' || (*str) == '-')) {
        if ((*str) == '-') {
            sign = -1;
        }
        ++str;
    }

    if (((*str) != '\0') &amp;&amp; (!isdigit(*str))) {
        return 0;
    }

    while (((*str) != '\0') &amp;&amp; (isdigit(*str))) {
        i = i * 10 + (*str - '0');
        j = i * sign;
        cout &lt;&lt; j &lt;&lt; endl;
        if (j &gt; INT_MAX) {
            return INT_MAX;
        }
        if (j &lt; INT_MIN) {
            return INT_MIN;
        }

        ++str;
    }

    return j;
}
You seem to have too many checks for '\0'. They don't add anything. Also too many brackets, but better too many than too few.

Also, is long long guaranteed to be bigger than int? I don't think it is. Here's another version that doesn't need a bigger representation than that of int: 

int atoi(const char *str)
{
    int n = 0;
    int sign = 1;

    while (isspace(*str)) {
        ++str;
    }
    if (*str == '-') {
        sign = -1;
        ++str;
    } else if (*str == '+') {
        sign = 1;
        ++str;
    }
    while (isdigit(*str)) {
        if (n &gt; INT_MAX/10) { /* EDIT: protect against overflow */
            break;
        }
        n *= 10;
        int ch = *str - '0';

        if (n &gt; INT_MAX - ch) {
            break;
        }
        n += ch;
        ++str;
    }
    if (isdigit(*str)) {
        return sign == 1 ? INT_MAX : INT_MIN;
    }
    return sign * n;
}


EDIT: I added a check to prevent overflow of the n *= 10

EDIT2: improved to avoid using an unsigned int - it was a hack