8、String to Integer (atoi)

来源:互联网 发布:ubuntu mac lrzsz 编辑:程序博客网 时间:2024/05/17 02:13

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.

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.


 Math String

int atoi(const char *str) {        //暂时我还不清楚atoi函数的作用        //把字符串转换为整数,那么首先得确定哪些是可以转换的,并且转换出来的整数溢出怎么办,数据溢出时,取极值        /* 1、字符串前面有空格,需要将空格去掉         * 2、第一个非空格字符是正号、符号或数字(包括0开头的数字)         *         */        bool pos = true;        int index = 0;        while (str[index] == ' ')            ++index;        if (str[index] == '+')        {            pos = true;            ++index;        }        else if (str[index] == '-')        {            pos = false;            ++index;        }        int result = 0, temp = INT_MAX / 10;        while (str[index] <= '9' && str[index] >= '0')        {            if (result > temp || result < 0 )            {                result = -1;//表明数据溢出                break;            }            result = result * 10 + str[index] - '0';            ++index;        }        if (result < 0)            return pos == true ? INT_MAX : INT_MIN;        else            return pos == true ? result : -result;    }

int atoi(const char *str) {       //使用long long不用考虑数据溢出        bool pos = true;        int index = 0;        while (str[index] == ' ')            ++index;        if (str[index] == '+')        {            pos = true;            ++index;        }        else if (str[index] == '-')        {            pos = false;            ++index;        }        long long result = 0;        while (str[index] <= '9' && str[index] >= '0' && result <= INT_MAX)            result = result * 10  + str[index++] - '0';        if (result > INT_MAX)            return pos == true ? INT_MAX : INT_MIN;        else            return pos == true ? result : -result;                }


0 0