您的位置:首页 > 其它

【leetcode系列】String to Integer (atoi)

2014-08-06 09:05 274 查看
这个我就直接上代码了,最开始把“abc123“也算作合法的了,后来查了一下atoi的定义,把这种去掉了。

public class Solution {
public static int atoi(String inStr) {
long result = 0L;
/*
* 网上查了一下,atoi函数的定义是如果第一个非空格字符存在,是数字或者正负号则开始做类型转换,
* 之后检测到非数字(包括结束符\0)字符时停止转换,返回整型数。否则,返回零。可能的输入情况有: 1、空字符串
* 2、"123abc"、"1a2b3c"、"abc123"、"-123abc" 3、溢出 4、有空格
*/
// step1:过滤空格
inStr = inStr.trim();
char[] inCharArray = inStr.toCharArray();
int index = 0;
// step2:正负号
char flag = '+';
if (inCharArray[0] == '+' || inCharArray[0] == '-') {
flag = inCharArray[0];
index = 1;
}
// step3:转换和各种判断
for (int i = index; i < inCharArray.length; i++) {
if (Character.isDigit(inCharArray[i])) {
result = result * 10 + Integer.parseInt(inCharArray[i] + "");
} else {
break;
}
}
// step4:带上正负号
if (flag == '-') {
result = -result;
}
// step5:是否溢出
if (result > Integer.MAX_VALUE) {
result = Integer.MAX_VALUE;
} else if (result < Integer.MIN_VALUE) {
result = Integer.MIN_VALUE;
}
return (int) result;
}

public static void main(String[] args) {
// System.out.println(Integer.MAX_VALUE + "" + Integer.MIN_VALUE);
String[] testCase = { "123abc", "+123abc", "-123abc", " 123abc ",
"abc123", "1ab2c3", "2222222222", "-2222222222" };
for (String test : testCase) {
System.out.print(atoi(test));
System.out.println();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode atoi