LeetCode---(8)String to Integer (atoi)
来源:互联网 发布:淘宝差评语 编辑:程序博客网 时间:2024/06/17 07:53
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.
首先,字符串开始的空白字符要跳过,并且需要记录首字母是‘+’‘-’或者直接就是数字,以此来判断正负数。
其次,对于转换结果,我们知道整型数据的范围是INT_MIN(-2147482648)到INT_MAX(2147483647),超出范围则返回最大与最小值。所以我们可以开始用long long类型的变量存储结果;
class Solution {public: int myAtoi(string str) { if(str.size()==0) return 0; long long res=0; int flag=1; int i=0; while(str[i]==' ') i++; if(str[i]=='+') i++; else if(str[i]=='-'){ flag=-1; i++; } for(int j=i;j<str.size();j++) { if(str[j]<='9'&&str[j]>='0') { res=res*10+(str[j]-'0'); if(res>INT_MAX) return flag>0?INT_MAX:INT_MIN; } else break; } return res*flag; }};
0 0
- LeetCode 8 - String to Integer (atoi)
- [LeetCode 8] String to Integer (atoi)
- leetcode 8STRING TO INTEGER (ATOI)
- 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 8:《String to Integer (atoi) 》
- leetcode.8---------------String to Integer (atoi)
- leetCode #8 String to Integer (atoi)
- [LeetCode Java] 8 String to Integer (atoi)
- 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 8 - String to Integer (atoi)
- leetcode #8 String to Integer (atoi)
- String to Integer (atoi) - LeetCode 8
- idea
- CRF++的初步使用(1)
- IIS6.0的默认权限和用户权限设置小结
- 黑马程序员_java 反射的基本理解
- Hibernate检索方式
- LeetCode---(8)String to Integer (atoi)
- 为 JIRA 6.x 安装中文语言包
- 最小生成树之Kruskal算法
- 2015年7月10日 UITableView 2
- poj 2231 Moo Volume
- 含有过滤功能的android流式布局
- 新增button控件为其添加onClick事件及Text
- 7.10垫底总结
- View Controller、Delegate、TextField——《iOS编程》第六、七章学习笔记