8 String to Integer (atoi)

Implementation 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.

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.

int myAtoi(string str) {

    // rid of spaces
    int integral_start = 0;
    while (str[integral_start] == ' ') integral_start++;

    // a sign or digit must come next
    if (!(isdigit(str[integral_start]) || str[integral_start] == '-' || str[integral_start] == '+'))
        return 0;

    // obtain sign (if any) - assume positive
    bool is_pos = str[integral_start] == '-' ? false : true;
    bool has_sign = str[integral_start] == '-' || str[integral_start] == '+';

    // must be a digit after sign
    if (has_sign) {
        integral_start++;
        if (integral_start >= str.size() || !(isdigit(str[integral_start]))) return false;
    }

    // obtain all digits that come next
    int integral_end = integral_start;
    while (integral_end < str.size() && isdigit(str[integral_end])) integral_end++;
    integral_end--;

    // form the result - everything after becomes discarded
    long long int result = 0;
    long long int base_mult = 1;

    for (int i = integral_end; i >= integral_start; i--) {
        result += (str[i] - '0') * base_mult;
        base_mult *= 10;
    }

    return is_pos ? result : -1 * result;
}

Last updated