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

来源:互联网 发布:java程序流程图实例 编辑:程序博客网 时间:2024/05/17 05:18

题目

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 )

7 0
原创粉丝点击