首页 > 代码库 > [LeetCode] String to Integer (atoi) [7]
[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.
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; } };
另外,我开通了微信公众号--分享技术之美,我会不定期的分享一些我学习的东西.