[LeetCode] String to Integer (atoi) [7]

題目

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.

spoilers alert... click to show requirements for atoi.

Requirements for atoi:

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

原題鏈接

解題思路

這是個老題目了,主要考察的是能不能考慮到所有的情況,還有就是怎麼判斷是否溢出。
情況大致分爲如下四種:(下面我使用@代替空格,x代表除數字之外的所有字符, [+-]表示出現其中一個或者都不出現)

1. "@@[+-]3232343@@"

2. "@@[+-]333x54"

3. "@@[+-]4343"

4. "2147483648"或者"-2147483649"(也就是溢出的情況)

下面代碼中給出了兩個判斷是否溢出的方法。

代碼實現

class Solution {
public:
    int atoi(const char *str) {
        if(str==NULL) return 0;
        while(*str == ' ') ++str;
        if( *str == '\0' ) return 0;
        int minus = 1;
        if(*str == '+')
            ++str;
        else if(*str == '-'){
            minus = -1;
            ++str;
        }
        int ret = 0, pre = 0;
        while(*str != '\0'){
            if(!isdigit(*str)) return ret;
            if( !VerifyOverflow(pre) ){
                if(minus>0) return 0x7fffffff;
                return 0x80000000;
            }
            pre = pre*10 + (*str-'0')*minus;
            //還要判斷在10*pre不溢出時,其加上0-9的數是否溢出
            if(ret>0 && pre<0)
                return 0x7fffffff;
            if(ret<0 && pre>0)
                return 0x80000000;
            ret = pre;
            ++str;
        }
        return ret;
    }
    //判斷key*10是否溢出
    bool VerifyOverflow(int key){
        int mul = key*10;
        return !key || mul/key==10;
    }
};
如果你覺得本篇對你有收穫,請幫頂。
另外,我開通了微信公衆號--分享技術之美,我會不定期的分享一些我學習的東西.
你可以搜索公衆號:swalge 或者掃描下方二維碼關注我

(轉載文章請註明出處: http://blog.csdn.net/swagle/article/details/28679335 )

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章