【Leetcode】String to Integer (atoi)
2016-06-06 20:34
232 查看
题目链接:https://leetcode.com/problems/string-to-integer-atoi/
题目:
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.
思路:
各种边界会烦死人的。。。
算法:
[java] view
plain copy
public int myAtoi(String str) {
if (str == null || str.equals(""))
return 0;
str = str.trim();
String flag = "+";
int i = 0;
if ("+".equals(str.charAt(0) + "")) {
i++;
flag = "+";
} else if ("-".equals(str.charAt(0) + "")) {
i++;
flag = "-";
}
double sum = 0;
while (i < str.length() && str.charAt(i) <= '9' && str.charAt(i) >= '0') {
sum = sum * 10 + Integer.parseInt("" + str.charAt(i));
i++;
}
if (flag.equals("-")) {
sum = -sum;
}
if (sum > Integer.MAX_VALUE) {
sum = Integer.MAX_VALUE;
}
if (sum < Integer.MIN_VALUE) {
sum = Integer.MIN_VALUE;
}
return (int) sum;
}
题目:
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.
思路:
各种边界会烦死人的。。。
算法:
[java] view
plain copy
public int myAtoi(String str) {
if (str == null || str.equals(""))
return 0;
str = str.trim();
String flag = "+";
int i = 0;
if ("+".equals(str.charAt(0) + "")) {
i++;
flag = "+";
} else if ("-".equals(str.charAt(0) + "")) {
i++;
flag = "-";
}
double sum = 0;
while (i < str.length() && str.charAt(i) <= '9' && str.charAt(i) >= '0') {
sum = sum * 10 + Integer.parseInt("" + str.charAt(i));
i++;
}
if (flag.equals("-")) {
sum = -sum;
}
if (sum > Integer.MAX_VALUE) {
sum = Integer.MAX_VALUE;
}
if (sum < Integer.MIN_VALUE) {
sum = Integer.MIN_VALUE;
}
return (int) sum;
}
相关文章推荐
- 逻辑回归(Logistic Regression)
- OkHttp 3.0之后版本GET、POST请求以及POST上传文件的示例代码
- 如何远程访问svn 服务器
- PopupWindow+ListView
- 【Leetcode】Length of Last Word
- listView
- 垃圾收集器
- malloc、zalloc、calloc
- .NET-Dictionary索引重载 赋值时允许Key不存在
- SpringEmail with Velocity template date and number formatting
- 第十三周上机实践项目:阅读、修改和运行关于交通工具类的程序(2)
- radioButton的简单使用
- 根据身份证算出地址
- Flip Game
- centos安装redis3为系统服务
- 更新资源文件
- js之select二级联动
- 你不知道的全文检索---solr索引库的维护(一)
- NI(美国国家仪器)二面
- fastDFS架构解析和安装测试教程