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' && isspace(*str)) {        ++str;    }    if (((*str)!='\0') && ((*str) == '+' || (*str) == '-')) {        if ((*str) == '-') {            sign = -1;        }        ++str;    }    if (((*str) != '\0') && (!isdigit(*str))) {        return 0;    }    while (((*str) != '\0') && (isdigit(*str))) {        i = i * 10 + (*str - '0');        j = i * sign;        cout << j << endl;        if (j > INT_MAX) {            return INT_MAX;        }        if (j < INT_MIN) {            return INT_MIN;        }        ++str;    }    return j;}
string to integer (implement atoi)
c;strings;interview questions
if (((*str) != '\0') && (!isdigit(*str))) {    return 0;}You don't need this condition, because of the condition in the while loop afterwards. If that fails the first time j with value 0 is returned anyway.And a minimal (and maybe unnecessary) optimization:if (j >= INT_MAX) {    return INT_MAX;}if (j <= INT_MIN) {    return INT_MIN;}Why look for the next character in the string which would only get appended to the number and would increase the value, if the number already has the maximumk/minimum value possible (INT_MAX/INT_MIN).