LeetCode : String to Integer (atoi) [java]
2016-03-05 16:32
381 查看
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.
思路:考虑前后空格,正负号,为空等输入情况,考虑溢出,使用long类型判断当前值是否已经溢出。
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.
思路:考虑前后空格,正负号,为空等输入情况,考虑溢出,使用long类型判断当前值是否已经溢出。
public class Solution { public int myAtoi(String str) { if (str == null || str.equals("")) { return 0; } String myStr = str.trim(); int max = Integer.MAX_VALUE; int min = Integer.MIN_VALUE; long result = 0; int isPositive = 1; int index = 0; char begin = myStr.charAt(0); if (begin == '-') { isPositive = -1; index = 1; } if(begin == '+'){ index = 1; } for (int i = index; i < myStr.length(); i++) { char ch = myStr.charAt(i); if (ch > '9' || ch < '0') { return (int) result * isPositive; } else { result = result * 10 + ch - '0'; if (result > max || result < min) { return isPositive == 1 ? max : min; } } } return (int) result * isPositive; } }
相关文章推荐
- Mac安装Myeclipse2015开发环境
- java,关于POJO,查阅资料
- JDK中常用包简要说明
- 白话Spring(基础篇)---AOP(execution表达式)
- java,编写一个汽车类
- Java基础之内存
- java基础题汇总
- [Java基础] 抽象类和接口的区别
- SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-002- 在xml中引用Java配置文件,声明DispatcherServlet、ContextLoaderListener
- java特种兵读书笔记(5-7)——编写并发程序要注意什么
- java算法复杂度
- java初步学习之堆栈
- 关于JavaBean
- Java String的部分源码学习
- 使用Maven创建Java web工程
- Java Web学习(四)
- LeetCode : Reverse Integer [java]
- Java复习笔记(三)——文档注释
- win10怎么安装JDK8,怎么配置JDK8的环境变量
- eclipse快捷键