[Leetcode 8, Easy] String to Integer

来源:互联网 发布:logmett是什么软件 编辑:程序博客网 时间:2024/06/05 17:40

Problem:

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.

Analysis:

This problem does not have many tricks in programming. The main goal of this problem is how to convert the very large number.The basic idea in such questions is using unsigned variable to take the absolute value of an integer.An unsigned variable can take 2 times of the range of an integer variable. The sign of the integer should be delt with seperately, and combine it to the return value in the end. This trick is a common trick in programming.

Solution:

C++:

int atoi(const char *str) {        if(strlen(str) == 0)            return 0;        int validStart = 0;        bool isNegative = false;        for(; validStart < strlen(str); ++validStart) {            if(str[validStart] == ' ')                continue;            if((str[validStart] >= '0' && str[validStart] <= '9'))                break;            else if(str[validStart] == '+') {                ++validStart;                break;            } else if(str[validStart] == '-') {                isNegative = true;                ++validStart;                break;            } else                return 0;        }                if(validStart == strlen(str))            return 0;                int validEnd = validStart;        for(; validEnd < strlen(str); ++validEnd)            if(str[validEnd] < '0' || str[validEnd] > '9') {                if(validEnd == validStart)                    return 0;                --validEnd;                break;            }        if(validEnd == strlen(str))            --validEnd;        if(validEnd - validStart + 1 > 10)            return isNegative ? INT_MIN : INT_MAX;        unsigned int absolute = 0;                for(int i = validStart; i <= validEnd; ++i)            absolute = absolute * 10 + str[i] - '0';                if(absolute > (isNegative ? INT_MIN : INT_MAX))            return isNegative ? INT_MIN : INT_MAX;                return isNegative ? (-1)* absolute : absolute;    }
Java:


Python:

0 0
原创粉丝点击