leetcode string to integer

class Solution {
public:
    int atoi(const char *str)
    {
        int total;         /* current total */
        char sign;           /* if '-', then negative, otherwise positive */
        while ( isspace(*str) )
            ++str;
        if (*str == '-' || *str == '+')
            sign = *str++;    /* skip sign */

        total = 0;
        while (isdigit(*str)) {
            if((INT_MAX-(*str-'0'))/10<total)
            {
                total=sign=='-'?INT_MIN:INT_MAX;
            }
            else total = 10 * total + (*str - '0');     /* accumulate digit */
            str++;    /* get next char */
        }
        if (sign == '-')
        {
            total=-total;
        }
        return total;   /* return result, negated if necessary */       
    }
};

 

判断溢出还可以使用long long类型

 

posted @ 2013-05-22 17:01  代码改变未来  阅读(188)  评论(0编辑  收藏  举报