首页 > 其他 > 详细

String to Integer (atoi)

时间:2015-03-27 10:44:34      阅读:155      评论: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.

题目只考虑了"    123"或者"+123","-123",而不考虑"abs123"等情况,所以一开始只要排除空格,然后直接判断正负号,接着读取数字字符即可。

但是要考虑溢出,int占四个字节,32位,取值范围是-2147483648~2147483647;

若超过了负数则 输出-2147483648  超过了正数则输出2147483647
在科普一个知识点,倘若某个数超过了2147483647则会变为负数,反过来一样

int myAtoi(char *str) {
    while(*str == 32) str++;
    if((*str != - && *str != +) && (*str < 0 || *str >9)) return 0;
    int t = 1;
    long long result = 0;
    if(*str == -){
        t = -1;
        str++;
    }else if(*str == +){
        str++;
    }
    while(*str >= 0 && *str <= 9){
        result = result*10 + (*str - 0);
        if(t == -1 && result >= 2147483648){
            result = 2147483648;
            break;
        }
        if(result > 2147483647){
            result = 2147483647;
            break;
        }
        str++;
    }
    result *= t;
    return result;
}

 

String to Integer (atoi)

原文:http://www.cnblogs.com/zhhc/p/4371046.html

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