String——string-to-integer-atoi
2016-05-13 17:26
351 查看
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.
Analysis
The following cases should be considered for this problem:
啊实打实的
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.
Analysis
The following cases should be considered for this problem:
1. null or empty string 2. white spaces 3. +/- sign 4. calculate real value 5. handle min & max
public class Solution { public int atoi(String str) { if(str == null||str.trim().length() == 0) return 0; str=str.trim();//考虑前后有空格的出现 char[]ch=str.toCharArray(); long sum=0; int flag=1; for(int i=0;i<ch.length;i++) { if(ch[i]<'0'||ch[i]>'9') { if(i == 0) { if(ch[i] == '+') continue; else if(ch[i] == '-') { flag=-1; continue; } else break;//"123a123"这种情况,打印123 } else break; } sum=sum*10+ch[i]-'0'; } sum=sum*flag; if(sum>Integer.MAX_VALUE) return Integer.MAX_VALUE; if(sum<Integer.MIN_VALUE) return Integer.MIN_VALUE; return (int)sum; } }
啊实打实的
相关文章推荐
- CentOS 设置 Tomcat 开机自动启动
- HttpServletRequest.getHeader() 详细说明
- [wpf]如果根据其他控件改变按钮的Path样式
- DNN、CNN、RNN简析
- 移动端web页面如何适配
- 几种常见的Android自动化测试框架及其应用
- **OA项目——问题集
- python里面的高级特性
- c++中箭头操作符(->)和点操作符(.)的不同
- 算法06 之2-3-4树
- Java内存泄露简述
- 传统的Ado.net 参数设置:params SqlParameter[] commandParameters
- mac开机启动原理--apache
- 【杂项】时刻提醒自己:Markdown使用方法
- JVM -XX: 参数介绍
- MQTT+ApolloServer实现Android的消息推送功能
- AES加密算法实现
- 博客换到自己的个人网站
- python核心编程第二版中的网络爬爬虫修改
- java中文乱码解决之道(七)—–JSP页面编码过程