LeetCode String to Integer (atoi)
来源:互联网 发布:初中课本同步软件 编辑:程序博客网 时间:2024/05/27 14:13
Implement atoi to convert a string to an integer.
Requirements for atoi:
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
坑有点多,要考虑到所有情况,从正负号(如果有的话)之后遇到不是数字的字符就结束。我是先用字符串把整理过后标准的形式存起来,然后用字符串的比较来判断是否溢出。
class Solution {public: int myAtoi(string str) { string s, int_max("2147483647"), int_min("2147483648"); int i = 0, p = 1; int res = 0; while (str[i] == ' ') i++; if(str[i] == '+') i++; else if(str[i] == '-'){ p = -1; i++; } if(str[i] < '0' || str[i] > '9') return 0; for(; i < str.size(); i++){ if(str[i] >= '0' && str[i] <= '9') s += str[i]; else break; } if(p == 1){ if(s.size() > int_max.size() || ((s.size() == int_max.size())&&s >= int_max)) return 2147483647; } if(p == -1){ if(s.size() > int_max.size() || ((s.size() == int_max.size())&&s >= int_min)) return -2147483648; } for(int k = 0; k < s.size(); k++){ res = res*10 + (s[k]-'0'); } res = res * p; return res; }};
- 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)
- VS2008快捷键
- iOS coding多人协作开发工具
- 综合性实验五、有限状态机的硬件描述语言设计方法
- java反射机制+继承设计技巧
- Android让ListView记住上次滑动到的位置
- LeetCode String to Integer (atoi)
- SDWebImage的使用
- Android利用JDBC连接服务器数据库
- ThinkPHP 实现将SESSION存 mysql db方式session
- static 与变量的关系
- Android编程规范不完全指南
- 程序设计语言的构成
- UWP开发之StreamSocket聊天室(三)
- 独乐乐不如众乐乐