Leetcode -- String to Integer (atoi)
来源:互联网 发布:淘宝网妈妈冬装 编辑:程序博客网 时间:2024/04/30 20:33
问题链接:https://oj.leetcode.com/problems/string-to-integer-atoi/
问题描述:Implement atoi to convert a string to an integer.
API: public int atoi(String str)
分析:这连续几题都是数学题,这一题其实也不是很难。难的只是输入的不确定性,因为不能保证输入的合法。但根据spoiler(看链接)给出的提示和限定条件,只需要先用String.trim()去掉前后空格,判断第一位是否正负符号,然后不停往下走,遇到数字就算,遇到其他字符便停。overflow的检测和刚才Reverse Integer是一样的。
下面给出代码:
public int atoi(String str) { str = str.trim(); int isNeg = 0; if(str.length() == 0) return 0; if(str.charAt(0) == '+') isNeg = 1; else if(str.charAt(0) == '-') isNeg = -1; int res = 0; int check = 0; for(int i = isNeg == 0 ? 0 : 1; i < str.length(); i++){ char cur_bit = str.charAt(i); if(cur_bit <= '9' && cur_bit >= '0'){ int cur_bit_num = (int)(cur_bit - '0'); res *= 10; res += cur_bit_num * (isNeg == -1 ? -1 : 1); if(res / 10 != check){ return isNeg == -1 ? Integer.MIN_VALUE : Integer.MAX_VALUE; } check = res; }else{ break; } } return res; }
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)
- SVN 如何提交 SO 库文件
- Leetcode subsets2
- android知识点:Activity的生命周期
- Linux学习笔记-基本的命令行操作
- 国税Tax2.0 运行时错误429:ActiveX部件不能创建对象的解决办法
- Leetcode -- String to Integer (atoi)
- 使用支持向量机(SVM)对数据分类
- 转载的开发者福利 ios开发的知识
- codeforces 498 e Stairs and Lines
- Linux下Socket编程学习(二)
- 消除控制台输出缺失首字母的方法
- ASP.NET对请求处理的过程
- Apache Commons Launcher简介
- Ubuntu12.04下安装Openvswitch