8. String to Integer (atoi)(8.46%)
2016-01-13 18:05
225 查看
题目: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.
个人理解:实现atoi方法将字符串转为整数。这道题没什么把握,题目本身也没说太明白,只是提到要考虑很多种输入情况。比如,检测到一个整数字符的时候,接下来如果出现空格,那么就截止,将当前已检测到的整数返回。
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.
个人理解:实现atoi方法将字符串转为整数。这道题没什么把握,题目本身也没说太明白,只是提到要考虑很多种输入情况。比如,检测到一个整数字符的时候,接下来如果出现空格,那么就截止,将当前已检测到的整数返回。
public class Solution { public int myAtoi(String str) { int result = 0; if (str == null || str.equals("")) { return result; } char[] inputStrs = str.toCharArray(); String temp = ""; boolean canContinue = true; boolean beginInput = false; for (char c : inputStrs) { if (c == ' ') { if (!beginInput && canContinue) { continue; } else { break; } } else if (c >= '0' && c <= '9') { temp += c; beginInput = true; } else if (c == '-' || c == '+'){ if (canContinue) { temp += c; canContinue = false; } else { break; } } else { break; } } if (temp.equals("+") || temp.equals("-")) { return 0; } if (temp.endsWith("+") || temp.endsWith("-")) { return 0; } if (!temp.equals("")) { try { result = Integer.parseInt(temp); } catch (Exception e) { // TODO: handle exception if (temp.contains("-")) { return Integer.MIN_VALUE; } else { return Integer.MAX_VALUE; } } } return result; } }
相关文章推荐
- ES6--API
- 测试工作——Native App, Web App 和 Hybrid app
- 文件结构体struct file(Linux 2.6.23内核) (转)
- Java-高精度
- QEMU内在:整体架构和线程模型
- Android串口通信:串口读写
- 如何正确的获得一个view的宽和高
- iReport5.6.0 linechart 制作方法
- [转] TF-IDF与余弦相似性的应用(二):找出相似文章
- spring启动component-scan类扫描加载过程---源码分析
- [Leetcode 98] Validate Binary Search Tree
- &&在shell
- iOS 初学者关于动态按钮代码创建
- Linux系统Mysql备份的导入导出
- Asoc dapm(一) - kcontrol
- 免费下载IEEE802系列标准
- java.io.NotSerializableException: java.util.ArrayList$SubList
- 数据结构.图.无向带权&邻接矩阵.最短路径Dijkstra算法
- python set集合操作
- 比较分析 Spring AOP 和 AspectJ 之间的差别