[LeetCode]8. 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.

方法

注意溢出、符号以及main()里其他的特殊情况

c代码

#include <assert.h>
#include <limits.h>

int myAtoi(char* str) {
    while(*str == ' ')
        str++;
    int sign = 1;
    if(*str == '-') {
        sign = -1;
        str++;
    }
    else if(*str == '+')
        str++;
    int result = 0;
    while(*str != '\0') {
        if(*str>='0' && *str<='9') {
            if((result > INT_MAX/10) || (result==INT_MAX/10 && *str>'7')) {
                if(sign == 1)
                    return INT_MAX;
                return INT_MIN;
            }
            result = result*10 + *str-'0';
        }
        else
            return sign*result;
        str++;
    }
    return sign*result;
}

int main() {
    assert(myAtoi("123111111") == 123111111);
    assert(myAtoi("a1") == 0);
    assert(myAtoi("      111111111111111111111") == INT_MAX);
    assert(myAtoi("-111111111111111111111111111") == INT_MIN);
    assert(myAtoi("123aaa") == 123);
    assert(myAtoi("-1") == -1);
    assert(myAtoi("+-2") == 0);

    return 0;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容