String to Integer (atoi)

题目描述:

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.

  

  这道题又涉及到整数处理,越界是必须要考虑的。一处理整数,我就想到栈,哎,代码写的太冗余了。贴下别人的吧

solution1:

int atoi(const char *str) {
    while (isspace(*str))
        ++str;
    int sign = (*str == '-') ? -1 : 1;
    if(*str == '-' || *str == '+')
        ++str;
    long long res = 0;
    while (isdigit(*str))
    {
        res = res * 10 + *str - '0';
        if (sign > 0 && res > INT_MAX)
            return INT_MAX;
        if(sign < 0 && -res < INT_MIN)
            return INT_MIN;
        ++str;
    }
    return res * sign;
}

  此法诀窍在于使用long long类型避免越界,如果不使用long long类型呢?

solution2:

int atoi(const char *str) {
    while (isspace(*str))
        ++str;
    int sign = 1;
    if (*str == '+' || *str == '-')
    {
        if (*str == '-')
            sign = -1;
        ++str;
    }

    int res = 0;
    while (isdigit(*str))
    {
        int digit = *str - '0';
        if (res > (INT_MAX - digit)/10)
            return sign == 1 ? INT_MAX : INT_MIN;
        res = res * 10 + digit;
        ++str;
    }
    return res * sign;
}

参考文章:http://blog.csdn.net/ithomer/article/details/8800530

类似文章:http://blog.csdn.net/linhuanmars/article/details/21145129

      https://oj.leetcode.com/discuss/8886/my-simple-solution

PS:

  另一个处理整数的算法题 Reverse Integer:http://www.cnblogs.com/gattaca/p/4177810.html

原文地址:https://www.cnblogs.com/gattaca/p/4190135.html