[Leetcode] 8. String to Integer (atoi) 解题报告
来源:互联网 发布:淘宝销量怎么算 编辑:程序博客网 时间:2024/06/09 18:45
题目:
Implement atoi to convert a string to an integer.
思路:
这是我见过的最简单的题目描述了。可是正因为简单,该题目的考点就在于我们如何实现算法使其能够鲁棒地处理各种情况。具体列举如下:
1)字符串开始前很可能有很多前导空格。前导空格应该被忽略。
2)字符串可能以正负符号开头,也可能直接以表示0-9之间的字符开头。这两种情况都合法。
3)在合法字符串结束之后可能还有其它非数字字符的存在。这些非数字字符均应该被忽略。
4)字符串本身无法被合法的转换,例如第一个非空格字符既非正负号,也非数字,或者字符串为空,或者字符串仅包含空格字符。此时应该返回0。
5)如果所转换出来的字符大于整数的表示范围,则返回整数的最大值(INT_MAX)或者最小值(INT_MIN)。
当然以上情况分别如何处理应该和面试官进行沟通,而不能自己想当然。前者一定会给你加分不少,后者如果处理不当则会减分不少。
代码:
class Solution {public: int myAtoi(string str) { int i = 0, flag = 1; long answer = 0; // in order to avoid overflow while(str[i] == ' ') i++; if(str[i] == '+' || str[i] == '-') flag = str[i++] == '+' ? 1 : -1; while(isdigit(str[i])) { answer = 10 * answer + (str[i++] - '0'); if(answer * flag > INT_MAX) return INT_MAX; else if(answer * flag < INT_MIN) return INT_MIN; } return flag * answer; }};Follow up:
如果需要转换的是浮点数,你的代码需要如何修改?如果还需要同时支持科学计数法呢?其实我记得Leetcode中是有一道类似于itof的题目的(65. Valid NUmber),读者可以参考。个人感觉这两道题目有共同的地方,而且难度依次递增,所以建议读者把这两道题目结合起来思考并练习。
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) 解题报告
- String to Integer (atoi) LeetCode 解题报告
- [leetcode] 8. String to Integer (atoi) 解题报告
- [Leetcode] 8. String to Integer (atoi) 解题报告
- leetcode解题报告8. String to Integer (atoi)
- 【Leetcode】8.String to Integer (atoi) 解题
- [LeetCode 解题报告]008.String to Integer (atoi)
- LeetCode(8) String to Integer (atoi)解题报告
- String to Integer (atoi)解题报告
- [Leetcode]解题文档-String to Integer (atoi)
- [LeetCode]8. String to Integer (atoi)
- LeetCode 8. String to Integer (atoi)
- 8. String to Integer (atoi) Leetcode Python
- LeetCode --- 8. String to Integer (atoi)
- java中的字节编码
- 字符串转时间格式
- 机器学习: TensorFlow with MLP 笑脸识别
- 移动应用实战(移动OA)之五_会议室管理之二
- Eclipse更改注释的模版
- [Leetcode] 8. String to Integer (atoi) 解题报告
- iOS数组遍历(enumerateObjectsUsingBlock)
- 拿到最新日期及前一天
- PHP技巧:了解比较运算符的不同
- 01python入门
- Spring 事务注解的使用(1)
- 牛客:剑指offer:丑数(Java)
- rtmp 视频包中的大小端问题
- Android中WebView的使用