又是一道充满坑的题目
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.
把字符串转成int,有几个点需要注意:1.超出int范围;
2.+-需要另外考虑,表示符号,之后第二个出现非数字,就结束;
3.开始的空格需要忽略,从第一个字符开始考虑;
public static int myAtoi(String str) {
List<Integer> list = new ArrayList<Integer>();
str = str.trim();//除去收尾的空格
int k = 0;
int l = 0;
double sum = 0;
int isNagetive = 1;
for(int i = 0;i < str.length(); i++) {
try{
if(str.charAt(i)=='-'){
isNagetive = -1;
k++;//统计出现的‘-’
}else if(str.charAt(i) == '+'){
l++;//统计出现的‘+’
}else if(k>1){
break;//减号出现两次,结束循环;
}else if(l>1){
break;//加好出现两次,结束循环;
}else if(l>0 && k>0){
break;//加减各出现一次,也结束循环
}else if(Integer.parseInt(str.charAt(i)+"")>=0 && Integer.parseInt(str.charAt(i)+"")<=9) {
list.add(Integer.parseInt(str.charAt(i)+""));
}
}catch(Exception e){
break;//出现既不是加好减号,也不是数字的字符,结束循环;
}
}
for(int i = 0;i < list.size();i++) {
sum = sum*10 + list.get(i);
}
sum = sum*isNagetive;
if(sum > Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
}
if(sum < Integer.MIN_VALUE) {
return Integer.MIN_VALUE;
}
return (int)sum;
}
代码很简单,但是问题一开始考虑不周全,提交了很多次才正确。