LeetCode-008 String to Integer (atoi)
来源:互联网 发布:淘宝的聚划算怎么抢 编辑:程序博客网 时间:2024/06/05 06:54
Description
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.
Analyse
题目很简单,就是让你把一个字符串转换为一个整型。题目越简单,出问题的几率越大,题目几乎什么都没说,连测试样例都没有给,根本有哪几种不合法的输入,被坑了若干遍之后,发现了这道题的所有的坑点。。。
(1)无视前面空格,若后面开始输入数字之后出现空格,直接终止算法,坑点。
(2)符号有‘+’和‘-’但是需要注意的是,符号只能出现一遍,若出现第二遍的话,直接终止算法,这是一个很大的坑点。
(3)若整数越界,则返回最接近该整数的边界,即最大32位整数或最小32位整数。
把上面三个问题处理妥当之后,这道题就很简单了,我在上面的坑浪费了很多的时间。
Code
class Solution {public: int myAtoi(string str) { int len=str.length(); int sign=1;//符号 long num=0; bool flag=false;//用来判断符号是否第一次出现 int i=0; while (i<len && str[i]==' ') i++;//去除前置空格 for (;i<len;i++) { if (str[i]=='-' && !flag) sign=-sign; if (str[i]>='0' && str[i]<='9') { num=num*10+(str[i]-'0'); if (sign*num>INT_MAX) return INT_MAX; if (sign*num<INT_MIN) return INT_MIN; } else { if ((str[i]=='+' || str[i]=='-') && !flag) { flag=true; } else break; } } return (int) sign*num; }};
阅读全文
0 0
- leetcode-008:String to Integer (atoi)
- LeetCode 008 String to Integer (atoi)
- [LeetCode OJ][008]String to Integer (atoi)
- LeetCode 008 String to Integer (atoi)
- [LeetCode]-008-String to Integer (atoi)
- LeetCode 008 String to Integer (atoi)
- 008 String to Integer (atoi) [Leetcode]
- LeetCode 008 String to Integer (atoi)
- LeetCode 008 String to Integer (atoi)
- leetcode-008-String to Integer (atoi)
- LeetCode-008 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)
- tcp建立连接为什么需要三次握手
- iptables
- Linux awk使用示例
- 王一三学习笔记 | 理解Java垃圾回收
- 数据结构与算法之LinkedList源码分析
- LeetCode-008 String to Integer (atoi)
- 计算几何模板
- [AGC005F]Many Easy Problems-FFT-容斥原理
- 圆周率 π 的求法(二)
- websocket,无法建立到 ws://... 服务器的连接
- 大数据量查询优化——数据库设计、SQL语句、JAVA编码
- C/C++遇到的问题及分析
- order by与group by与时间同时存在问题
- LeetCode-009 Palindrome Number