首页 > 其他 > 详细

String to Integer (atoi)

时间:2014-12-28 18:04:18      阅读:206      评论:0      收藏:0      [点我收藏+]

题目描述:

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 = (*str == -) ? -1 : 1;
    if(*str == - || *str == +)
        ++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

String to Integer (atoi)

原文:http://www.cnblogs.com/gattaca/p/4190135.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!