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;
最后又来了一个坑,尼玛,测试用例竟然有一个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
- LeetCode:String to Integer (atoi)
- LeetCode: String to Integer (atoi)
- LeetCode String to Integer(atoi)
- LeetCode :String to Integer (atoi)
- Leetcode: String to Integer (atoi)
- Leetcode : String to Integer (atoi)
- 【leetcode】String to Integer (atoi)
- [LeetCode]String to Integer (atoi)
- LeetCode-String to Integer (atoi)
- [leetcode] String to Integer (atoi)
- LeetCode - String to Integer (atoi)
- 【leetcode】String to Integer (atoi)
- LeetCode - String to Integer (atoi)
- LeetCode: String to Integer (atoi)
- Leetcode: String to Integer (atoi)
- [LeetCode] String to Integer (atoi)
- leetcode String to Integer (atoi)
- [LeetCode]String to Integer (atoi)
- 面试笔试杂项积累-leetcode 191-200
- Induction, Deduction and Reduction
- 【URAL 刷题记】URAL 1317 ~ URAL 1326
- pat1017
- Android逆向分析(一) - 反编译看看手Q口令红包的实现原理
- String to Integer(atoi) LeetCode
- Android 前后台切换与OpenGL(EGL)创建销毁的周期
- cvCalcBackProject() 直方图反向投影匹配
- uva 489刽子手游戏
- 大数减法
- HDU 3081 Marriage Match II(二分+并查集+最大流)
- C++继承的简单例程
- 蓝桥杯 BASIC-12 十六进制转八进制
- zookeeper使用和原理探究