[leetcode-8]String to Integer (atoi)(java)
2015-07-23 20:40
417 查看
问题描述:
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.
分析:首先,先对字符串进行一次过滤,将开头的空格去掉。然后在查找之后的,当遇到+-时后面一定要求是数字,也即不能是++或者+-或者-+或者–等情况。此外,更重要的一点是注意溢出现象。特别的当sum*10时发生溢出不好判断,因此,我设置了sum的阈值。当sum>这个阈值时,肯定会发生溢出。此时,再单独处理。
代码如下:404ms
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.
分析:首先,先对字符串进行一次过滤,将开头的空格去掉。然后在查找之后的,当遇到+-时后面一定要求是数字,也即不能是++或者+-或者-+或者–等情况。此外,更重要的一点是注意溢出现象。特别的当sum*10时发生溢出不好判断,因此,我设置了sum的阈值。当sum>这个阈值时,肯定会发生溢出。此时,再单独处理。
代码如下:404ms
[code] public int myAtoi(String str) { char tmp; int sum = 0; int i; boolean minus = false; boolean requireNumber = false; boolean overflow = false; //clear the space for(i = 0;i<str.length();i++){ if((tmp=str.charAt(i))!=' ') break; } for(;i<str.length();i++){ if((tmp=str.charAt(i))=='+'){ if(requireNumber) break; requireNumber = true; } else if(tmp=='-'){ if(requireNumber) break; requireNumber = true; minus = true; } else if(tmp>='0'&&tmp<='9'){ if(sum>Integer.MAX_VALUE/10){ sum = -1; }else sum = sum*10+tmp-'0'; if(sum<0){ sum = Integer.MAX_VALUE; overflow = true; } }else { break; } } if(overflow&&minus) return sum+1; else if(overflow) return sum; return minus?-sum:sum; }
相关文章推荐
- 单例模式(懒汉式和饿汉式)
- Eclipse调试Logcat类的说明
- Java设计模式之基本原则(二)
- struts2 redirect redirectAction chain区别
- Struts2_1_struts2建立一个执行环境
- 【Struts2框架】第二节Result-向结果传参数
- 【Struts2框架】第二节Result-动态结果集
- Java基础——面向对象——继承、抽象类、接口、多态、包、内部类、异常等
- knn算法计算位置电影的类型Java实现《机器学习实战》2.1节的例子
- 【Struts2框架】第二节Result-Global_Results_全局结果集
- 详解jar命令打包生成双击即可运行的Java程序
- [java]深入理解JVM内存模型
- 自定义struts(扩展)--将注解从action上移到service中
- Java创建文件要注意的一个问题
- Eclipse运行时出现Hot Code Replace Failed
- 【leetcode-36】valid sudoku(java)
- Java中单元测试中:@BeforeClass,@Before,@Test,@After,@AfterClass中的问题详解
- Java学习笔记--------为组建设置事件的步骤
- java 位操作
- Java构造器与多态