LeetCode题目:String to Integer (atoi)
来源:互联网 发布:淘宝优惠券从哪里来的 编辑:程序博客网 时间:2024/06/05 18:07
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.
这道题目是比较简单的字符串操作题目,但是题目中的坑还是挺多的,不认真做的话很难Accept ,下面贴代码:因为性能分析中运算时间达到了61ms,所以我的代码只适合给新手提供参考,如何提高性能还需要进一步的思考和修改。
class Solution { public int myAtoi(String str) { //先去前后空格,题目中前后有空格也算是有效格式 str = str.trim(); String origin = str; if(str.isEmpty()){ return 0; } //用StringBuilder来存储字符 StringBuilder strbuff = new StringBuilder();
//去掉正负号 if(str.startsWith("-")||str.startsWith("+")){ str=str.substring(1); System.out.println(str); } int temp =0; //获取数字,遇到非数字则终止 for(int i=0;i<str.length();i++){ temp = (int)str.charAt(i); if(temp>=48&&temp<=57){ strbuff.append(str.charAt(i)); }else{ break; } } if(strbuff.length()==0){ return 0; } int result = 0;
使用parseint进行解析,如果超出int值范围则返回Int 的最大值 try{ result = Integer.parseInt(strbuff.toString()); }catch(Exception e){ if(origin.startsWith("-")){ return -2147483648; }else{ return 2147483647; } } //判断正负 if(origin.startsWith("-")){ return 0-result; } return result; }}
阅读全文
0 0
- LeetCode算法题目:String to Integer (atoi)
- LeetCode题目:String to Integer (atoi)
- LeetCode题目: 8. String to Integer (atoi)
- LeetCode题目:String to Integer (atoi)
- leetcode String to Integer (atoi) -- 很无聊的题目
- 3.leetcode题目8: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)
- 程序中计时
- 语义分割学习笔记(二)——Windows下 Lableme 配置
- XGboost实例--数据处理
- MyEclipse 2014配置Maven
- 1033. 旧键盘打字(20)--Python
- LeetCode题目:String to Integer (atoi)
- javaweb连接池总结
- explicit & implicit
- HBase1.2.x安装部署(win8+jdk1.8+hadoop2.8.1 无需cygwin)
- Android蓝牙通讯(三)————蓝牙通讯的实现
- 基础练习 字母图形
- 任正非对话Fellow:华为如何迎接智能时代的挑战?
- 摩尔定律或在2021终结,这会是半导体厂商的噩梦?
- h5斗地主房卡源码下载斗地主游戏的示例代码分析