Stringto Integer(atoi) Algorithm

The String to Integer (atoi) algorithm is a widely-used function in programming languages like C and C++, designed to convert a given string into an integer value. The main purpose of the atoi function is to parse a string of characters representing a numeric value, evaluate its contents, and return the corresponding integer. This function is particularly useful in scenarios where a program needs to handle user input or data from external sources, which may not always come in the desired format, for instance, a user entering a number as text. The algorithm works by iterating through the given string, starting at the first character, and considering the following aspects: leading whitespace characters, an optional sign (either '+' or '-'), and a sequence of digits. The atoi function ignores leading whitespaces and stops processing when it encounters a non-digit character. If a valid sign is encountered, the algorithm processes the following digits accordingly. While iterating through the string, the algorithm updates an integer variable by multiplying its current value by 10 and adding the integer value of the current digit. This process continues until the end of the string or an invalid character is encountered. Finally, the algorithm returns the integer value obtained, taking into account the sign if present, and any applicable overflow or underflow conditions.
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;
        while (*str == ' ') {
            str++;
        }
        bool minus = false;
        if (*str == '+') {
            str++;
        } else if (*str == '-') {
            str++;
            minus = true;
        }
        long long int value = 0;
        for (; *str != '\0'; str++) {
            if ('0' <= *str && *str <= '9') {
                value *= 10;
                value += *str - '0';
            } else {
                break;
            }
        }
        if (minus)
            value = -value;
        if (value > INT_MAX)
            value = INT_MAX;
        if (value < INT_MIN)
            value = INT_MIN;
        return (int)value;
    }
};

LANGUAGE:

DARK MODE: