String to Integer(atoi) LeetCode

来源:互联网 发布:软件培训班 编辑:程序博客网 时间:2024/05/29 11:17

题目链接点击此处,题目描述如下:

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.

题目表面看起来比较简单,但是坑不少,什么滤除前缀空格、正负号就不提了。主要问题在于清楚理解数据的表示范围。

__int64 INT_MAX_P_1 = INT_MAX + 1;

并不能得到真正比INT_MAX大1的数字(由于INT_MAX是int,所以加1之后还是int,并没有自动的变为__int64),如果想加1之后自动变为__int64,需要分开写,即:

__int64 INT_MAX_P_1 = INT_MAX;INT_MAX_P_1 += 1;


再者,需要注意输入为INT_MIN时的处理,即输入为-2147483648时的处理

最后又来了一个坑,尼玛,测试用例竟然有一个65位的数字:"18446744073709551617"

思前想后,还是在将字符串转换为数字的时候,顺便记录转换后的长度,如果长度超过11位,同样根据isNative的符号,直接处理,完整代码:

int myAtoi(char* str) {long long int tmpResult = 0;int isNaive = 1;int result = 0;long long int ATOI(const char* str, int *length);int i = 0;int numLength = 0;    long long int INT_MAX_P_1 = INT_MAX;INT_MAX_P_1 += 1;//滤除空格for (i=0; ' ' == str[i]; ++i);if ('-' == str[i]){isNaive = -1;++i;}else if ('+' == str[i]){isNaive = 1;++i;}if (str[i] >= '0' && str[i] <= '9'){tmpResult = ATOI(&str[i], &numLength);}    if (tmpResult < 0 || INT_MAX_P_1 <= tmpResult || numLength >= 11){if (-1 == isNaive){result = INT_MIN;}else if (1 == isNaive){result = INT_MAX;}}else{result = isNaive * tmpResult;}return result;}long long int ATOI(const char* str, int *length){int i = 0;long long int result = 0;while (str[i] >= '0' && str[i] <= '9'){result = result * 10 + (str[i] - '0');++i;}(*length) = i;return result;}




0 0
原创粉丝点击