Implement atoi to convert a string to an integer.
这道题挺难的,很多意外情况没能考虑到,花了一个多小时才搞定,代码感觉还比较丑陋。
思路
- 字串为空或者全是空格,返回0;
- 字串的前缀空格需要忽略掉;
- 忽略掉前缀空格后,遇到的第一个字符,如果是‘+’或‘-’号(如果遇到多个’+’ / ‘-’ ,则返回0)继续往后读;如果是数字,则开始处理数字;如果不是前面的2种,返回0;
- 处理数字的过程中,如果之后的字符非数字,就停止转换,返回当前值;
- 在上述处理过程中,如果转换出的值超出了int型的范围,就返回int的最大值或最小值(关键步骤)
Runtime: 9 ms
public static int myAtoi(String str) {
int result = 0;
int flag = 0;
boolean isFirst = true;
StringBuilder sb = new StringBuilder();
char m;
int count = 0;
try {
for (int i = 0; i < str.length(); i++) {
m = str.charAt(i);
if (m == ' ' && isFirst) {
continue;
} else if (m == ' ' && !isFirst) {
break;
} else if ((m < 48 || m > 57) && (m != '-') && (m != '+')) {
break;
} else {
isFirst = false;
sb.append(m);
}
}
str = sb.toString();
if ((str.startsWith("+") || str.startsWith("-"))) {
if (str.startsWith("-") && str.substring(1).length() > 10) {
return -2147483648;
} else if (str.startsWith("+") && str.substring(1).length() > 10) {
return 2147483647;
}
if (str.length() == 11 && str.startsWith("+") && str.compareTo("2147483647") > 0) {
return 2147483647;
} else if (str.length() == 11 && str.startsWith("-") &&
str.substring(1).compareTo("2147483648") > 0) {
return -2147483648;
}
} else if (str.length() == 10) {
if (str.compareTo("2147483647") > 0) {
return 2147483647;
}
}else if(str.length() > 10) {
return 2147483647;
}
Stack<Integer> mStack = new Stack<Integer>();
Stack<Integer> bStack = new Stack<Integer>();
for (int i = 0; i < str.length(); i++) {
m = str.charAt(i);
if (count > 1) {
return 0;
}
if (m == '-') {
flag = 1;
count++;
continue;
} else if (m == '+') {
count++;
continue;
}
if (m < 48 || m > 57)
break;
else
mStack.push(m - '0');
}
if (mStack.size() == 0) {
return 0;
}
while (mStack.size() > 0) {
bStack.push(mStack.pop());
}
result = bStack.pop();
while (bStack.size() > 0) {
result = 10 * result + bStack.pop();
}
if (flag == 0)
return result;
else
return -result;
} catch (Exception e) {
}
return 0;
}